https://oj.leetcode.com/problems/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].
public List<List<Integer>> permute(int[] num)
问题分析:这题其实可以视作一个图论题,如果把所有元素都当做一个节点,其实就是要找以任意两个节点作为起点和终点经过所有点的所有路径。找所有路径是DFS比较合适一点。下面就给出一个DFS的算法。可以认为num[0]是起点,num[num.length - 1]是终点。然后num[1..i]就是中间的过程节点来看待就好,当走到终点的时候就记录一条路径。
public List<List<Integer>> permute(int[] num) {
List<List<Integer>> res = new LinkedList<List<Integer>>();
helper(res, 0, num);
return res;
}
public void helper(List<List<Integer>> res, int curlevel, int[] num){
if(curlevel == num.length){
LinkedList<Integer> cur_res = new LinkedList<Integer>();
for(int i : num)cur_res.add(i);
res.add(cur_res);
}
else{
for(int i = curlevel; i < num.length; i++){
int tmp = num[curlevel];
num[curlevel] = num[i];
num[i] = tmp;
helper(res, curlevel + 1, num);
num[i] = num[curlevel];
num[curlevel] = tmp;
}
}
}
这个做法是有点取巧的,达到了零空间,在Programming Interview Exposed里面给出了一个用boolean[num.length]做缓存记录当前节点是否走过的做法。本质上和这个其实是一样的。