-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCombinationSum.java
More file actions
27 lines (26 loc) · 1.04 KB
/
CombinationSum.java
File metadata and controls
27 lines (26 loc) · 1.04 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
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> combinations = new ArrayList<>();
List<Integer> possibleCombination = new ArrayList<>();
Arrays.sort(candidates);
combinationsSum(combinations, possibleCombination, candidates, target, 0);
return combinations;
}
public void combinationsSum(
List<List<Integer>> combinations,
List<Integer> possibleCombination,
int[] candidates,
int target,
int level
) {
if (target == 0) {
combinations.add(new ArrayList<Integer>(possibleCombination));
} else if (target > 0) {
for (int i = level; i < candidates.length; ++i) {
possibleCombination.add(candidates[i]);
combinationsSum(combinations, possibleCombination, candidates, target - candidates[i], i);
possibleCombination.remove(possibleCombination.size() - 1);
}
}
}
}