Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b0c7c09

Browse files
Add implementations for generating permutations and subsets of integers
1 parent b3d3670 commit b0c7c09

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

‎Recursion/Permutation.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
public class Permutation {
2+
public static void main(String[] args) {
3+
String str = "abc";
4+
generatePermutation(str, "");
5+
}
6+
7+
static void generatePermutation(String str, String newStr) {
8+
if (str.length() == 0) {
9+
System.out.println(newStr);
10+
return;
11+
}
12+
13+
for (int i = 0; i < str.length(); i++) {
14+
char currChar = str.charAt(i);
15+
String remaining = str.substring(0,i) + str.substring(i+1);
16+
17+
generatePermutation(remaining , currChar+newStr);
18+
19+
}
20+
}
21+
}

‎Recursion/Subset.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import java.util.ArrayList;
2+
3+
public class Subset {
4+
public static void main(String[] args) {
5+
ArrayList <Integer> subset = new ArrayList<>();
6+
int n = 3;
7+
findSubset(n, subset);
8+
9+
}
10+
static void findSubset(int n , ArrayList<Integer> subset){
11+
//base case
12+
if(n == 0){
13+
System.out.println(subset);
14+
return;
15+
}
16+
17+
//include the element
18+
subset.add(n);
19+
findSubset(n-1, subset);
20+
21+
//exclude the element
22+
subset.remove(subset.size() - 1);
23+
findSubset(n-1, subset);
24+
25+
26+
}
27+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /