-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path39.combination-sum.java
More file actions
44 lines (37 loc) · 1.21 KB
/
Copy path39.combination-sum.java
File metadata and controls
44 lines (37 loc) · 1.21 KB
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
/*
* @lc app=leetcode id=39 lang=java
*
* [39] Combination Sum
*/
// @lc code=start
class Solution {
protected void backtrack(
int remain,
LinkedList<Integer> comb,
int start,
int[] candidates,
List<List<Integer>> results) {
if (remain == 0) {
// make a deep copy of the current combination
results.add(new ArrayList<Integer>(comb));
return;
} else if (remain < 0) {
// exceed the scope, stop exploration.
return;
}
for (int i = start; i < candidates.length; ++i) {
// add the number into the combination
comb.add(candidates[i]);
this.backtrack(remain - candidates[i], comb, i, candidates, results);
// backtrack, remove the number from the combination
comb.removeLast();
}
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> results = new ArrayList<List<Integer>>();
LinkedList<Integer> comb = new LinkedList<Integer>();
this.backtrack(target, comb, 0, candidates, results);
return results;
}
}
// @lc code=end