-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPermutation.java
More file actions
50 lines (31 loc) · 1.08 KB
/
Copy pathPermutation.java
File metadata and controls
50 lines (31 loc) · 1.08 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
package JavaHowToProgram;
import java.util.ArrayList;
import java.util.List;
public class Permutation {
public static void main(String[] args){
String x = "ABCDEFGHIJ";
System.out.println(getPerms(x));
}
public static ArrayList<String> getPerms(String x){
ArrayList<String> allPerms = new ArrayList<>();
ArrayList<String> permutations = new ArrayList<>();
String s = "";
if(x.length() == 1) {
permutations.add(x);
return permutations;
}
for(int i = 0; i < x.length(); i++) {
s = "" + x.charAt(i);
String swap = swap(x, i);
ArrayList<String> temp = getPerms(swap.substring(1, swap.length()));
for(int j = 0; j < temp.size(); j++){
String perm = s + temp.get(j);
allPerms.add(perm);
}
}
return allPerms;
}
private static String swap(String y, int ind){
return y.substring(ind, ind + 1) + y.substring(0, ind) + y.substring(ind + 1 , y.length());
}
}