-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC39-CombinationSum.java
More file actions
37 lines (27 loc) · 1.06 KB
/
Copy pathLC39-CombinationSum.java
File metadata and controls
37 lines (27 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
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
// Empty case
if(candidates == null || candidates.length == 0) return result;
Arrays.sort(candidates);
backtrack(candidates, target, result, new ArrayList<>(), 0);
return result;
}
private void backtrack(int[] inputs, int remaining, List<List<Integer>> result, List<Integer> currentList, int startIndex) {
// Combination found
if(remaining == 0) {
result.add(new ArrayList<>(currentList));
return;
}
// Continue on with the loop
for(int i = startIndex; i < inputs.length; i++) {
// Input bigger than the remaining buffer
if(inputs[i] > remaining) {
break;
}
currentList.add(inputs[i]);
backtrack(inputs, remaining - inputs[i], result, currentList, i);
currentList.remove(currentList.size() - 1);
}
}
}