Given a collection of numbers that might contain duplicates, return all possible unique permutations.
代码如下:
public class Solution {
public List<List<Integer>> permutenique(int[] nums){
List<List<Integer>> result=new ArrayList<>();
if (nums.length>0){
Arrays.sort(nums);
permute(nums,0,new ArrayList<>(),result);
}
return result;
}
private void permute(int nums[], int next, List<Integer> tmp, List<List<Integer>> result) {
if (next==nums.length){
result.add(new ArrayList<>(tmp));
}else{
Set<Integer> s=new HashSet<>();
for (int i=next;i<nums.length;i++){
if (!s.contains(nums[i])){
swap(nums,i,next);
tmp.add(nums[next]);
permute(nums,next+1,tmp,result);
tmp.remove(tmp.size()-1);
s.add(nums[i]);
}
}
}
}
void swap(int[] A, int i, int j) {
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}