-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutation.java
More file actions
49 lines (43 loc) · 1.32 KB
/
Permutation.java
File metadata and controls
49 lines (43 loc) · 1.32 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
package permutation;
import java.util.ArrayList;
import java.util.List;
public class Permutation {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> list = new ArrayList<>();
for(int i = 0; i < nums.length; i++){
list.add(nums[i]);
}
result.add(list);
for(int i = 0; i < nums.length-1; i++){
int length = result.size();
for(int j = i+1; j < nums.length; j++){
for(int k = 0; k < length; k++){
result.add(change(i,j,result.get(k)));
}
}
}
return result;
}
public List<Integer> change(int begin, int end, List<Integer> list){
List<Integer> result = new ArrayList<>();
for(int i = 0; i < list.size(); i++){
result.add(list.get(i));
}
int t = result.get(begin);
result.set(begin, result.get(end));
result.set(end, t);
return result;
}
public static void main(String[] args){
Permutation t = new Permutation();
int[] nums = new int[]{1,2,3};
List<List<Integer>> result = t.permute(nums);
for(int i = 0; i < result.size(); i++){
for(int j = 0; j < nums.length; j++){
System.out.print(result.get(i).get(j)+",");
}
System.out.println();
}
}
}