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]
]
包含重复数的排列组合问题。
思路与上一题一样,关键在于利用
if(i>0 &&nums[i-1]==nums[i] && !used[i-1]) continue;
来跳过重复数的递归。
public class Solution {
public List<List<int>> PermuteUnique(int[] nums) {
List<List<int>> res = new List<List<int>>();
if(nums==null || nums.Length==0) return res;
bool[] used = new bool[nums.Length];
List<int> list = new List<int>();
Array.Sort(nums);
dfs(nums, used, list, res);
return res;
}
public void dfs(int[] nums, bool[] used, List<int> list, List<List<int>> res){
if(list.Count()==nums.Length){
res.Add(new List<int>(list));
return;
}
for(int i=0;i<nums.Length;i++){
if(used[i]) continue;
if(i>0 &&nums[i-1]==nums[i] && !used[i-1]) continue;
used[i]=true;
list.Add(nums[i]);
dfs(nums,used,list,res);
used[i]=false;
list.RemoveAt(list.Count()-1);
}
}
}