1、题目:
链接:permutations
Given a collection of numbers, return all possible permutations.
For example,
[1,2,3]have the following permutations:
[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2], and[3,2,1].
2、思路:是全排列问题,需要列出所有可能的情况n!种。用递归实现,例如在下面代码中,由num[index]开始,作为第一个元素,有num.length - index个元素可以填充,假如第一个是i = index+2,将index和i位置交换,确定了第一个元素,剩下的元素就调用permu(num, index+1):
for(int i = index; i < num.length; i++){
swap(num,index,i);
permu(num, index+1);
swap(num,index,i);
}
3、代码:
public class Permutations {
private ArrayList<ArrayList<Integer>> res;
public ArrayList<ArrayList<Integer>> permute(int[] num) {
res = new ArrayList<ArrayList<Integer>>();
Arrays.asList(num);
permu(num,0);
return res;
}
private void permu(int[] num, int index) {
if(num.length - 1 == index){
ArrayList<Integer> list =new ArrayList<Integer>();
for(int t:num)
list.add(t);
res.add(list);
return;
}
for(int i = index; i < num.length; i++){
swap(num,index,i);
permu(num, index+1);
swap(num,index,i);
}
}
private void swap(int[] num, int index, int i) {
int t = num[index];
num[index] = num[i];
num[i] = t;
}
}