-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombsum(recursion)
More file actions
40 lines (36 loc) · 1.06 KB
/
Copy pathCombsum(recursion)
File metadata and controls
40 lines (36 loc) · 1.06 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
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
backtrack(0, candidates, target, new ArrayList<>(), ans);
return ans;
}
private void backtrack(int index,
int[] candidates,
int target,
List<Integer> curr,
List<List<Integer>> ans) {
if (target == 0) {
ans.add(new ArrayList<>(curr));
return;
}
if (target < 0 || index == candidates.length) {
return;
}
curr.add(candidates[index]);
backtrack(
index,
candidates,
target - candidates[index],
curr,
ans
);
curr.remove(curr.size() - 1);
backtrack(
index + 1,
candidates,
target,
curr,
ans
);
}
}