-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
32 lines (28 loc) · 1.08 KB
/
Solution.java
File metadata and controls
32 lines (28 loc) · 1.08 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
package combinationSum;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> combinations = new ArrayList<>();
List<Integer> prefix = new ArrayList<>();
backtracking(combinations, prefix, 0, 0, candidates, target);
return combinations;
}
private void backtracking(List<List<Integer>> combinations, List<Integer> prefix, int preSum, int index, int[] candidate, int target) {
if (preSum == target && !prefix.isEmpty()) {
combinations.add(new ArrayList<>(prefix));
return;
}
for (int i = index; i < candidate.length; i++) {
if (preSum + candidate[i] <= target) {
prefix.add(candidate[i]);
backtracking(combinations, prefix, preSum + candidate[i], i, candidate, target);
prefix.remove(prefix.size() - 1);
} else {
break;
}
}
}
}