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 class Solution {
public List<List<Integer>> permute(int[] num) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
helper(res, list, num);
return res;
}
private void helper(List<List<Integer>> res, List<Integer> list, int[] num) {
// base 条件:如果完成一个序列,则把该list加入 结果集
if (list.size() == num.length) {
res.add(new ArrayList<Integer>(list));
return;
}
for (int i = 0; i < num.length; i++) {
//如果num[i]已经放入list,则跳出此次循环,进入下一次循环
if (list.contains(num[i])){
continue;
}
list.add(num[i]);
//list存入num[i]后,再进行同样的递归操作,一直到 list 长度为 num.length
helper(res, list, num);
//一定要记得remove操作,执行到此处代表着 一条list已经完成,所以要对list进行处理,用来存储新的结果集
list.remove(list.size()-1);
}
return;
}
}做这种排列题目的一般写法是:
递归函数() {
base 条件判断;
for 循环 {
if 条件判断;
添加当前值;
递归进入下一层;
递归返回以后,remove 当前的节点,处理结果集的container,以便用来进行新一轮的操作
}
}
其他相似题目:
permutation II
subset
unique subset
971

被折叠的 条评论
为什么被折叠?



