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) { if (target <= 0 ){ if (target == 0 ) ans.add(new ArrayList<>(list)); return ; } for (int i = start; i < candidates.length;i++){ list.add(candidates[i]); target -= candidates[i]; backtricking(candidates,target,list,ans,i); list.remove(list.size() - 1 ); target += candidates[i]; } } }