-
Notifications
You must be signed in to change notification settings - Fork 112
/
090-Subsets2.cs
52 lines (46 loc) · 1.54 KB
/
090-Subsets2.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//-----------------------------------------------------------------------------
// Runtime: 296ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace LeetCode
{
public class _090_Subsets2
{
public IList<IList<int>> SubsetsWithDup(int[] nums)
{
var results = new List<IList<int>>() { new List<int>() };
if (nums.Length == 0) return results;
Array.Sort(nums);
results.Add(new List<int>() { nums[0] });
IList<IList<int>> lastAdded = new List<IList<int>>() { new List<int>() { nums[0] } };
for (var i = 1; i < nums.Length; i++)
{
var result = new List<IList<int>>();
if (nums[i] == nums[i - 1])
{
foreach (var item in lastAdded)
{
var newItem = new List<int>(item);
newItem.Add(nums[i]);
result.Add(newItem);
}
}
else
{
foreach (var item in results)
{
var newItem = new List<int>(item);
newItem.Add(nums[i]);
result.Add(newItem);
}
}
results.AddRange(result);
lastAdded = result;
}
return results;
}
}
}