版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ghscarecrow/article/details/86566936
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2] Output: [ [1,1,2], [1,2,1], [2,1,1] ]
思考:可能会出现重复的数字,对于该类数字,我们无需对这两个数字进行交换,所以需要利用到Set对原始元素进行去重判断
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if(nums.length <= 0){
return res;
}
Arrays.sort(nums);
dfs(res,nums,0);
return res;
}
public void dfs(List<List<Integer>> res,int[] nums,int row){
if(row == nums.length){
List<Integer> temp = new ArrayList<>();
for(Integer num:nums){
temp.add(num);
}
res.add(temp);
return;
}
Set<Integer> set = new HashSet<>();
for(int i=row;i<nums.length;i++){
if(set.add(nums[i])){
swap(nums,i,row);
dfs(res,nums,row+1);
swap(nums,i,row);
}
}
}
public void swap(int[] nums,int i,int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}