-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathCombinationSum.java
32 lines (28 loc) · 1.06 KB
/
CombinationSum.java
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
// https://leetcode.com/problems/combination-sum
// M = smallest candidate
// T: O(|candidates| ^ (target / M))
// S: O(target / M) // not sure tho --> if anyone has any idea please feel free to contact me
import java.util.ArrayList;
import java.util.List;
public class CombinationSum {
private final List<List<Integer>> result = new ArrayList<>();
private int[] candidates;
private int target;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
this.candidates = candidates;
this.target = target;
combinationSum(new ArrayList<>(), 0, 0);
return result;
}
public void combinationSum(List<Integer> current, int sum, int index) {
if (sum == target) {
result.add(current);
return;
} else if (sum > target) return;
for (int i = index ; i < candidates.length ; i++) {
List<Integer> newCandidate = new ArrayList<>(current);
newCandidate.add(candidates[i]);
combinationSum(newCandidate, sum + candidates[i], i);
}
}
}