forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path40-Combination-Sum-II.cs
More file actions
39 lines (32 loc) · 919 Bytes
/
40-Combination-Sum-II.cs
File metadata and controls
39 lines (32 loc) · 919 Bytes
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
public class Solution
{
//T: O(2^T), where T is target
public IList<IList<int>> CombinationSum2(int[] candidates, int target)
{
var result = new List<IList<int>>();
Array.Sort(candidates);
void dfs(int pos, Stack<int> current, int target)
{
if (target == 0)
{
result.Add(current.ToList());
}
if (target <= 0)
{
return;
}
var prev = -1;
for (var i = pos; i < candidates.Length; i++)
{
if (candidates[i] == prev)
continue;
current.Push(candidates[i]);
dfs(i + 1, current, target - candidates[i]);
current.Pop();
prev = candidates[i];
}
}
dfs(0, new Stack<int>(), target);
return result;
}
}