因为不考虑重复,就是不停的往一个ArrayList里面插数。
例如 1 2 3 4,现在想加入5.
就在5个不同的位置加入5. 成为 51234, 15234, 12534, 12354, 12345
难的在permutation2.稍后就写2.
NonRecursion Version:
public ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
result.add(new ArrayList<Integer>());
//Adding each element to the result
for (int i=0; i<num.length; i++) {
ArrayList<ArrayList<Integer>> current = new ArrayList<ArrayList<Integer>>();
//Adding the element to each permutation (e.x, 3 [1, 2])
for (ArrayList<Integer> perm : result) {
//Adding the element to each place for each location
for (int j=0; j<=perm.size();j++) {
perm.add(j,num[i]);
ArrayList<Integer> temp = new ArrayList<Integer>(perm);
current.add(temp);
perm.remove(j);
}
}
result = new ArrayList<ArrayList<Integer>>(current);
}
return result;
}
No comments:
Post a Comment