leetcode-46. Permutations
题目:
Given a collection of distinct 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],
[3,2,1]
]
之前做过类似的题目,但是和这题思路还是有很大差别的。
这一题的基本思路就是典型的回溯法。但是问题是怎么去查询下一层迭代。基本的方法就是每次加入不同的pos位置,然后如果List本身包含了这个pos的值则说明已经加入过了。
当然这是针对这题的,如果是有重复值的话就比较麻烦了。目前的思路和之前一题有类似的情况,就是先排序然后判断当前pos和pos-1是否一致来跳过相同的加入。这样的思路行不行。不过这个我没写过了。以后有时间需要实践一下。
public class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
helper(ret,nums,new ArrayList<Integer>());
return ret;
}
private void helper(List<List<Integer>> ret, int[] nums, ArrayList<Integer> list){
if(list.size()==nums.length){
ret.add(new ArrayList<Integer>(list));
return;
}
for(int i = 0 ; i < nums.length ; i++){
if(list.contains(nums[i])) continue;
list.add(nums[i]);
helper(ret,nums,list);
list.remove(list.size()-1);
}
}
}