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]
]
思路:大绝招
public class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
traceback(list,temp,nums);
return list;
}
public void traceback(List<List<Integer>> list, List<Integer> temp, int[] nums){
if (temp.size()==nums.length){
list.add(new ArrayList<Integer>(temp));
}else{
for (int i=0;i<nums.length;i++){
if (temp.contains(nums[i])) continue;
temp.add(nums[i]);
traceback(list,temp,nums);
temp.remove(temp.size()-1);
}
}
}
}
另一种写法:
public class Solution{
public List<List<Integer>> permute(int[] nums){
List<List<Integer>> res = new LinkedList<List<Integer>>();
if(nums == null || nums.length == 0){
return res;
}
permuteHelper(res, new LinkedList<Integer>(), nums, new HashSet<Integer>());
return res;
}
public void permuteHelper(List<List<Integer>> res, List<Integer> clist, int[]nums, HashSet<Integer> set){
if(clist.size()==nums.length){
res.add(new LinkedList<Integer>(clist));
}else{
for(int i = 0; i< nums.length; i++){
if(!set.contains(nums[i])){
clist.add(nums[i]);
int last = clist.size() - 1;
set.add(nums[i]);
permuteHelper(res,clist,nums,set);
set.remove(nums[i]);
clist.remove(last);//index, not value
}
}
}
}
}