forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path39-Combination-Sum.cs
31 lines (26 loc) · 923 Bytes
/
39-Combination-Sum.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
public class Solution {
IList<IList<int>> result = new List<IList<int>>();
public void backtrack(int index, List<int> path, int total, int[] candidates, int target) {
if(total == target) {
result.Add(path.ToList());
return;
}
if(total > target || index >= candidates.Length) return;
path.Add(candidates[index]);
backtrack(index,
path,
total + candidates[index],
candidates,
target);
path.Remove(path.Last());
backtrack(index + 1,
path,
total,
candidates,
target);
}
public IList<IList<int>> CombinationSum(int[] candidates, int target) {
backtrack(0, new List<int>(), 0, candidates, target);
return result;
}
}