-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombo_sum.java
More file actions
30 lines (24 loc) · 870 Bytes
/
combo_sum.java
File metadata and controls
30 lines (24 loc) · 870 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
class Solution {
private int[] candidates;
private int target;
private List<List<Integer>> result;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
this.candidates = candidates;
this.target = target;
this.result = new ArrayList<>();
backtrack(0, new ArrayList<>(), 0);
return result;
}
private void backtrack(int start, List<Integer> currentCombo, int currentSum) {
if (currentSum == target) {
result.add(new ArrayList<>(currentCombo));
return;
}
if (currentSum > target) return;
for (int i = start; i < candidates.length; i++) {
currentCombo.add(candidates[i]);
backtrack(i, currentCombo, currentSum + candidates[i]);
currentCombo.remove(currentCombo.size() - 1);
}
}
}