47. Permutations II
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,[1,1,2]have the following unique permutations:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
思路:大绝招
public class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
Arrays.sort(nums);
boolean[] used = new boolean[nums.length];
traceback(list,temp,nums,used);
return list;
}
public void traceback(List<List<Integer>> list,List<Integer> temp,int[] nums, boolean[] used){
if (temp.size()==nums.length){
list.add(new ArrayList<Integer>(temp));
}else{
for (int i=0;i<nums.length;i++){
if (used[i]||i>0&&nums[i]==nums[i-1]&&!used[i-1]) continue;
used[i] = true;
temp.add(nums[i]);
traceback(list,temp,nums,used);
used[i] = false;
temp.remove(temp.size()-1);
}
}
}
}