-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
/
Copy pathSolution.cs
38 lines (36 loc) · 1.04 KB
/
Solution.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System.Collections.Generic;
using System.Linq;
public class Solution {
public IList<IList<int>> PermuteUnique(int[] nums) {
var results = new List<IList<int>>();
var temp = new List<int>();
var count = nums.GroupBy(n => n).ToDictionary(g => g.Key, g => g.Count());
Search(count, temp, results);
return results;
}
private void Search(Dictionary<int, int> count, IList<int> temp, IList<IList<int>> results)
{
if (!count.Any() && temp.Any())
{
results.Add(new List<int>(temp));
return;
}
var keys = count.Keys.ToList();
foreach (var key in keys)
{
temp.Add(key);
--count[key];
if (count[key] == 0) count.Remove(key);
Search(count, temp, results);
temp.RemoveAt(temp.Count - 1);
if (count.ContainsKey(key))
{
++count[key];
}
else
{
count[key] = 1;
}
}
}
}