-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy path39-combination-sum.java
33 lines (31 loc) · 1.02 KB
/
39-combination-sum.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
33
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
dfs(res, candidates, target, new ArrayList<>(), 0, 0);
return res;
}
public void dfs(List<List<Integer>> res, int[] candidates, int target, List<Integer> path, int total, int idx) {
if (total == target) {
res.add(new ArrayList<>(path));
return;
}
if (total > target) {
return;
}
for (int i = idx; i < candidates.length; i++) {
path.add(candidates[i]);
total += candidates[i];
dfs(res, candidates, target, path, total, i);
path.remove(path.size() - 1);
total -= candidates[i];
}
}
}
// time O(n ** (T/S)), T is target number, and S is the min number in candidates
// space O(T/S), due to recursion stack
// using dfs and backtracking and subset
/*
1. type: subset
2. duplicate elements: no
3. selectable repeatedly: yes
*/