題目
給出一組候選數(shù)字(C)和目標(biāo)數(shù)字(T),找出C中所有的組合市殷,使組合中數(shù)字的和為T秦叛。C中每個(gè)數(shù)字在每個(gè)組合中只能使用一次新荤。
注意事項(xiàng)
所有的數(shù)字(包括目標(biāo)數(shù)字)均為正整數(shù)荧嵌。
元素組合(a1, a2, … , ak)必須是非降序(ie, a1 ≤ a2 ≤ … ≤ ak)慰枕。
解集不能包含重復(fù)的組合具则。
樣例
給出一個(gè)例子,候選數(shù)字集合為[10,1,6,7,2,1,5] 和目標(biāo)數(shù)字 8 ,
解集為:[[1,7],[1,2,5],[2,6],[1,1,6]]
代碼
public class Solution {
/**
* @param num: Given the candidate numbers
* @param target: Given the target number
* @return: All the combinations that sum to target
*/
public List<List<Integer>> combinationSum2(int[] candidates,
int target) {
List<List<Integer>> results = new ArrayList<>();
if (candidates == null || candidates.length == 0) {
return results;
}
Arrays.sort(candidates);
List<Integer> combination = new ArrayList<Integer>();
helper(candidates, 0, combination, target, results);
return results;
}
private void helper(int[] candidates,
int startIndex,
List<Integer> combination,
int target,
List<List<Integer>> results) {
if (target == 0) {
results.add(new ArrayList<Integer>(combination));
return;
}
for (int i = startIndex; i < candidates.length; i++) {
if (i != startIndex && candidates[i] == candidates[i - 1]) {
continue;
}
if (target < candidates[i]) {
break;
}
combination.add(candidates[i]);
helper(candidates, i + 1, combination, target - candidates[i], results);
combination.remove(combination.size() - 1);
}
}
}