forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCombinationSum.java
64 lines (48 loc) · 1.6 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
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
// @saorav21994
// Simple Backtracking
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
backtrack(candidates, res, 0, target, new ArrayList<>());
return res;
}
public void backtrack(int [] candidates, List<List<Integer>> res, int index, int target, List<Integer> cur) {
if (target == 0) {
res.add(new ArrayList<>(cur));
return;
}
if (target < 0 || index == candidates.length) {
return;
}
// skip current element
backtrack(candidates, res, index+1, target, cur);
// take current element
cur.add(candidates[index]);
backtrack(candidates, res, index, target-candidates[index], cur);
cur.remove(cur.size()-1);
}
}
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
if(candidates.length==0){
return res;
}
combinationSumHelper(candidates, target, 0, new ArrayList<Integer>(), 0);
return res;
}
private void combinationSumHelper(int[] candidates, int target, int currSum, List<Integer> subList, int index){
if(index>=candidates.length || (currSum > target)){
return ;
}
if(currSum == target){
res.add(new ArrayList<>(subList));
return ;
}
for(int i=index;i<candidates.length;i++){
subList.add(candidates[i]);
combinationSumHelper(candidates, target, currSum + candidates[i], subList, i);
subList.remove(subList.size()-1);
}
}
}