Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C Where the candidate numbers sums to T.
The same repeated number is chosen from C unlimited number of times.
Note:
- All numbers (including target) would be positive integers.
- Elements in a combination (a1, a 2, ..., aK) must is in non-descending order. (ie, a1≤ a2≤ ... ≤ ak).
- The solution set must not contain duplicate combinations.
For example, given candidate set and 2,3,6,7 target 7 ,
A Solution set is:
[7]
[2, 2, 3]
Thinking: Using backtracking and recursion
list<list<integer>> lists =NewArraylist<list<integer>>(); PublicList<list<integer>> Combinationsum (int[] candidates,inttarget) {Arrays.sort (candidates); if(target = = 0 | | candidates = =NULL|| Candidates.length = = 0) { returnlists; } combinationsumhelper (candidates, Target,0,NewArraylist<integer>()); returnlists; } Public voidCombinationsumhelper (int[] candidates,intTargetintStart, list<integer>list) { for(intI=start; i<candidates.length; i++) { if(Target >Candidates[i]) {List.add (candidates[i]); Combinationsumhelper (candidates, Target-Candidates[i], I, list); List.remove (List.size ()-1); } Else if(target = =Candidates[i]) {List.add (candidates[i]); Lists.add (NewArrayList (list)); List.remove (List.size ()-1); return; } Else { return; } } }
LeetCode-39 Combination Sum