forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path39-Combination-Sum.java
More file actions
29 lines (26 loc) · 865 Bytes
/
39-Combination-Sum.java
File metadata and controls
29 lines (26 loc) · 865 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 {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
List<Integer> cur = new ArrayList();
backtrack(candidates, target, ans, cur, 0);
return ans;
}
public void backtrack(
int[] candidates,
int target,
List<List<Integer>> ans,
List<Integer> cur,
int index
) {
if (target == 0) {
ans.add(new ArrayList(cur));
} else if (target < 0 || index >= candidates.length) {
return;
} else {
cur.add(candidates[index]);
backtrack(candidates, target - candidates[index], ans, cur, index);
cur.remove(cur.get(cur.size() - 1));
backtrack(candidates, target, ans, cur, index + 1);
}
}
}