Leetcode 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]
]

 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 }

 

 

 

 
 

转载于:https://www.cnblogs.com/liangmou/p/7807476.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值