Combination Sum

Leetcode 39.

In order to achieve the unique combinations of candidates, for loop should start with the specified value named start. This operation is usually called Pruning

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
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {

List<List<Integer>> ans = new ArrayList<>();
List<Integer> list = new ArrayList<>();
backtricking(candidates,target,list,ans,0);
return ans;
}
public void backtricking(int[] candidates,int target, List<Integer> list,List<List<Integer>> ans,int start){
//recursion stop condition
if(target <= 0){
if(target == 0)
ans.add(new ArrayList<>(list));
return;
}

//for loop for this layer
//for loop start with the specified value named start
//Pruning
for(int i = start; i < candidates.length;i++){
//process the nodes
list.add(candidates[i]);
target -= candidates[i];
//recursion
backtricking(candidates,target,list,ans,i);
//undo the previous operations
list.remove(list.size() - 1);
target += candidates[i];
}

}
}