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] ]
This solution beats 100% C# submmisions.
1 public class Solution { 2 public IList<IList<int>> PermuteUnique(int[] nums) { 3 var result = new List<IList<int>>(); 4 DFS(nums, 0, new List<int>(), result); 5 return result; 6 } 7 8 private void DFS(int[] nums, int start, IList<int> result, IList<IList<int>> results) 9 { 10 if (start >= nums.Length) 11 { 12 var r = new List<int>(result); 13 results.Add(r); 14 return; 15 } 16 17 var hashset = new HashSet<int>(); 18 19 for (int i = start; i < nums.Length; i++) 20 { 21 if (!hashset.Contains(nums[i])) 22 { 23 result.Add(nums[i]); 24 Swap(nums, start, i); 25 DFS(nums, start + 1, result, results); 26 Swap(nums, start, i); 27 result.RemoveAt(result.Count - 1); 28 hashset.Add(nums[i]); 29 } 30 } 31 } 32 33 private void Swap(int[] nums, int i, int j) 34 { 35 if (i != j) 36 { 37 var tmp = nums[i]; 38 nums[i] = nums[j]; 39 nums[j] = tmp; 40 } 41 } 42 }