排列

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
import java.util.ArrayList;
public class {
// ArrayList<int> 不行
// ArrayList<Integer[]> 可以
// ArrayList<Integer> 可以
//排列 (交换 递归)
public static ArrayList<int[]> permutation(int[] arr){
ArrayList<int[]> res = new ArrayList<int[]>(); // 将结果都保存在res中
if(arr == null || arr.length==0)
return null;
perm(res, 0, arr);
return res;
}
public static void perm(ArrayList<int[]> res, int i, int[] arr){
if(i==arr.length-1){
// 不能直接赋arr,因为arr是引用类型,res里的结果会全部一样的
res.add(arr.clone());
}else{
for(int j=i; j<arr.length; ++j){
swap(arr, i, j);
perm(res, i+1, arr);
swap(arr, i, j);
}
}
}
public static void swap(int[] str, int i, int j) {
if (i != j) {
int t = str[i];
str[i] = str[j];
str[j] = t;
}
}
public static void main(String[] args) {
int[] arr = {1,2,3,4};
int[] tmp;
ArrayList<int[]> res;
res = permutation(arr);
for(int i=0; i<res.size(); ++i){ // 输出所有的结果
tmp = res.get(i);
for(int j=0; j<tmp.length; ++j)
System.out.print(tmp[j]+" ");
System.out.println();
}
System.out.println(res.size());
}
}