-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy path039-CombinationSum.cs
43 lines (37 loc) · 1.32 KB
/
039-CombinationSum.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
//-----------------------------------------------------------------------------
// Runtime: 236ms
// Memory Usage: 32.5 MB
// Link: https://leetcode.com/submissions/detail/403607959/
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace LeetCode
{
public class _039_CombinationSum
{
public IList<IList<int>> CombinationSum(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)
{
for (int i = startIndex; i < candidates.Length; i++)
{
if (candidates[i] > gap) { return; }
tempResult.Add(candidates[i]);
if (candidates[i] == gap)
{
result.Add(new List<int>(tempResult));
}
else
{
DeepFirstSearch(candidates, gap - candidates[i], i, tempResult, result);
}
tempResult.RemoveAt(tempResult.Count - 1);
}
}
}
}