The original title link is here: https://leetcode.com/problems/combination-sum/
The topic and combinations, permutations, n-queens are recursive backtracking problems.
Target candidates one number at a time and then invokes helper recursively, target set to Target-candidates[i]. The termination condition of the recursion is target = = 0 o'clock added to the copy of item, target < 0 indicates that it has been reduced, and return directly.
Note:1. The topic said to be small to big, so don't forget the candidates sort.
2. For example, if target is 3,candidates = [+], in order not to return [1,2],[2,1] Two duplicate values, the recursive call is required to join the qualifying start. Each loop, I starts the loop.
3. Add the IF (i>0 && candidates[i] = = Candidates[i-1] in the loop continue; It is because the subject allows the use of repeating elements, if the following elements are the same, you can no longer do this calculation.
e.g. if candidates = [1,1,2], Target is 3, then multiple groups [1,1,1] will be returned.
AC Java:
1 Public classSolution {2 PublicList<list<integer>> Combinationsum (int[] candidates,inttarget) {3list<list<integer>> res =NewArraylist<list<integer>>();4 if(Candidates = =NULL|| Candidates.length = = 0){5 returnRes;6 }7 Arrays.sort (candidates);8Helper (candidates,target,0,NewArraylist<integer>(), res);9 returnRes;Ten } One Private voidHelperint[] candidates,intTargetintStart, list<integer> item, list<list<integer>>Res) { A if(target = = 0){ -Res.add (NewArraylist<integer>(item)); - return; the } - if(Target < 0){ - return; - } + for(inti = start; i<candidates.length; i++){ - //you can use repeating elements here, so if the next element is the same as the previous element, there is no need to judge the next element's input, wasting time + if(i>0 && candidates[i] = = Candidates[i-1]){ A Continue; at } - Item.add (Candidates[i]); -Helper (candidates,target-candidates[i],i,item,res); -Item.remove (Item.size ()-1); - } - } in}
Leetcode Combination Sum