Given A collection of candidate numbers (C) and a target number (T), find all unique combinations in cwhere the candidate numbers sums to T.
Each number in C is used once in the combination.
Notice
- All numbers (including target) would be positive integers.
- Elements in a combination (A1, A2, ..., AK) must is in non-descending order. (ie, a1≤a2≤ ... ≤ak).
- The solution set must not contain duplicate combinations.
Given candidate set [10,1,6,7,2,1,5]
and target 8
,
A Solution set is:
[ [1,7], [1,2,5], [2,6], [1,1,6]]
Public classSolution {/** * @paramNum:given the candidate numbers *@paramTarget:given the target number *@return: All the combinations, sum to target*/ PublicList<list<integer>> combinationSum2 (int[] num,inttarget) { //Write your code hereList<List<Integer>> result =NewArraylist<list<integer>>(); if(num = =NULL|| Num.length = = 0) returnresult; List<Integer> line =NewArraylist<integer>(); Boolean[] visited =New Boolean[Num.length]; Arrays.sort (num); Helper (result, line, NUM, Target, visited,0); returnresult; } Public voidHelper (list<list<integer>> result, list<integer> line,int[] num,intTargetBoolean[] visited,intstart) { if(Target < 0) return; if(target = = 0) {Result.add (NewArraylist<integer>(line)); return; } for(inti = start; i < num.length; i++){ if(i > 0 && num[i] = = Num[i-1] &&!visited[i-1]) Continue; Line.add (Num[i]); Visited[i]=true; Helper (result, line, NUM, Target-Num[i], visited, i + 1); Line.remove (Line.size ()-1); Visited[i]=false; } return; } }
Lintcode-medium-combination Sum II