Given A set of candidate numbers (c) and a target number (T), find all unique combinations in C where the candidate Nu Mbers sums to t.the same repeated number is chosen from C unlimited number of times. Note:all numbers (including target) would be positive integers. The solution set must not contain duplicate combinations. For example, given candidate set [2, 3, 6, 7] and Target 7, A solution set is: [ [7], [2, 2 , 3]]
For this kind of backtracking topic, still have to understand the choice, the limit, and the end of the condition are what respectively.
Public classSolution { PublicList<list<integer>> Combinationsum (int[] candidates,inttarget) { if(candidates==NULL|| Candidates.length==0){ return NULL; } //Arrays.sort (candidates);List<list<integer>> res=NewArraylist<list<integer>>(); List<Integer> item=NewArraylist<integer>(); intlen=candidates.length; Backtracking (candidates, target,0, item, RES); returnRes; } Public voidBacktracking (int[] candidates,intTargetintStart, list<integer> item, list<list<integer>>Res) { if(target<0){ return; } if(target==0) {Res.add (NewArraylist<integer>(item)); return; } for(intI=start; i<candidates.length; i++){ if(I>0 && candidates[i]==candidates[i-1]){ Continue; } item.add (Candidates[i]); Backtracking (candidates, target-Candidates[i], I, item, RES); //go to a dead end, return to the last stateItem.remove (Item.size ()-1); } } }
Leetcode-combination Sum