-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathCombinationSum.java
More file actions
76 lines (56 loc) · 1.75 KB
/
CombinationSum.java
File metadata and controls
76 lines (56 loc) · 1.75 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// 0-1 recursion or choose/notChoose recursion
class Solution {
List<List<Integer>> result;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
this.result = new ArrayList<>();
helper(candidates, target, new ArrayList<>(), 0);
return result;
}
private void helper (int[] candidates, int target, List<Integer> path, int index) {
// base
if (target == 0) {
result.add(new ArrayList<>(path)); // copy
return;
}
if (target < 0 || candidates.length == index) {
return;
}
// logic
// not choose
helper(candidates, target, path, index + 1);
// choose
path.add(candidates[index]);
helper(candidates, target - candidates[index], path, index);
path.remove(path.size() - 1);
}
}
// for loop based recursion
class Solution {
List<List<Integer>> result;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
this.result = new ArrayList<>();
helper(candidates, target, new ArrayList<>(), 0);
return result;
}
private void helper (int[] candidates, int target, List<Integer> path, int pivot) {
// base
if (target == 0) {
result.add(new ArrayList<>(path)); // copy
return;
}
if (target < 0) {
return;
}
// logic
for (int i = pivot; i < candidates.length; i++) {
//action
path.add(candidates[i]);
//recurse
helper(candidates, target - candidates[i], path, i);
//backtrack
path.remove(path.size() - 1);
}
}
}
// Time = O(2^(M+N))
// Space = O(N)