-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinationSum.java
More file actions
40 lines (33 loc) · 1.37 KB
/
CombinationSum.java
File metadata and controls
40 lines (33 loc) · 1.37 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
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
/**
the core logic is to explore all the combination leadig to achieve to target
so we can pick each ele( or say index ) as many times so
for every index we will call recursively with two options either to pick
the element and not pick the ele
with that in mind lets start coding :)
*/
// list to store all valid combination
List<List<Integer>> result = new ArrayList<>();
//recursively picking and not picking each index
recursively(candidates, target, 0, new ArrayList<>(), result);
return result;
}
private void recursively(int[] candidates, int target, int index, List<Integer> curr, List<List<Integer>> res){
//small(); cond.
if(target == 0){
res.add(new ArrayList<>(curr));
return ;
}
//iterating arr
for(int i = index; i < candidates.length; i++){
if(candidates[i] <= target) {
curr.add(candidates[i]);
//adding curr i till get target 0 or not
recursively(candidates, target - candidates[i], i, curr, res);
//after backtrack remove last inserted index ele value
curr.remove(curr.size() - 1);
}
}
}
}