-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathPermutation.java
More file actions
67 lines (51 loc) · 1.72 KB
/
Permutation.java
File metadata and controls
67 lines (51 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package strings;
import java.util.ArrayList;
public class Permutation{
public static void main(String[] args) {
// permutations("", "abc");
// ArrayList<String> ans = permutationList("", "abc");
// System.out.println(ans);
System.out.println(permutationsCount("","abc"));
}
public static void permutations(String p, String up){
if(up.length()==0){
System.out.println(p);
return;
}
char ch = up.charAt(0);
for (int i= 0; i<=p.length(); i++){
String f = p.substring(0, i);
String s = p.substring(i, p.length());
permutations(f+ch+s, up.substring(1));
}
}
static ArrayList<String> permutationList(String p, String up){
if(up.length()==0){
ArrayList<String> list = new ArrayList<>();
list.add(p);
return list;
}
char ch = up.charAt(0);
// local to this call
ArrayList<String> ans = new ArrayList<>();
for (int i= 0; i<=p.length(); i++){
String f = p.substring(0, i);
String s = p.substring(i, p.length());
ans.addAll(permutationList(f+ch+s, up.substring(1)));
}
return ans;
}
static int permutationsCount(String p, String up){
if(up.length()==0){
return 1;
}
char ch = up.charAt(0);
int count = 0;
for (int i= 0; i<=p.length(); i++){
String f = p.substring(0, i);
String s = p.substring(i, p.length());
count = count + permutationsCount(f+ch+s, up.substring(1));
}
return count;
}
}