-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
34 lines (27 loc) · 969 Bytes
/
Copy pathSolution.java
File metadata and controls
34 lines (27 loc) · 969 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
30
31
32
33
34
import java.util.ArrayList;
import java.util.List;
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
backtrack(0, candidates, 0, target, new ArrayList<>(), result);
return result;
}
private void backtrack(int start, int[] candidates, int sum, int target, List<Integer> current,
List<List<Integer>> result) {
if (sum > target) {
return;
}
if (sum == target) {
result.add(new ArrayList<>(current));
return;
}
for (int i = start; i < candidates.length; i++) {
if (sum + candidates[i] > target) {
continue;
}
current.add(candidates[i]);
backtrack(i, candidates, sum + candidates[i], target, current, result);
current.remove(current.size() - 1);
}
}
}