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].
分析:
全排列问题,这是两道题里第一道,即没有重复元素的全排列。
回溯问题,DFS。
具体思路是:
尝试将数组的每一个元素放在第一个位置,然后再对后面的元素进行全排列,这样就可以列出所有情况。
public class Solution {
public List<List<Integer>> permute(int[] num) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(num == null || num.length==0)
return res;
dfs(res, num, 0);
return res;
}
private void dfs(List<List<Integer>> res, int[] num, int start){
//当后面没有元素的时候,递归搜索结束,这时候num数组里存放的就是一个排列
if(start == num.length){
res.add(arrayToList(num));
return;
}
for(int i=start; i<num.length; i++){
//尝试将所有元素放在第一个位置
swap(num, start, i);
//递归得对后面元素全排列
dfs(res, num, start+1);
//恢复现场
swap(num, start, i);
}
}
private List arrayToList(int[] num){
List<Integer> list = new ArrayList<Integer>();
for(int i=0; i<num.length; i++){
list.add(num[i]);
}
return list;
}
private void swap(int[] num, int index1, int index2){
int temp = num[index1];
num[index1] = num[index2];
num[index2] = temp;
}
}