-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy path040-CombinationSum2.cs
46 lines (40 loc) · 1.41 KB
/
040-CombinationSum2.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
//-----------------------------------------------------------------------------
// Runtime: 484ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace LeetCode
{
public class _040_CombinationSum2
{
public IList<IList<int>> CombinationSum2(int[] candidates, int target)
{
Array.Sort(candidates);
var result = new List<IList<int>>();
DeepFirstSearch(candidates, target, 0, new List<int>(), result);
return result;
}
void DeepFirstSearch(int[] candidates, int gap, int startIndex, IList<int> tempResult, IList<IList<int>> result)
{
int previous = -1;
for (int i = startIndex; i < candidates.Length; i++)
{
if (candidates[i] == previous) { continue; }
if (candidates[i] > gap) { return; }
previous = candidates[i];
tempResult.Add(candidates[i]);
if (candidates[i] == gap)
{
result.Add(new List<int>(tempResult));
}
else
{
DeepFirstSearch(candidates, gap - candidates[i], i + 1, tempResult, result);
}
tempResult.RemoveAt(tempResult.Count - 1);
}
}
}
}