标签:
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
For example, given candidate set 10,1,2,7,6,1,5
and target 8
,
A solution set is: [1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
这题和Combination Sum一样,唯一的区别是每个元素只能用一次,而且如果元素里如果有同样的,则都可以用,比如 ([1,1], 2),输出[1],[1]
public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
if (candidates == null || candidates.length == 0) {
return result;
}
Arrays.sort(candidates);
helper(candidates, 0, target, new ArrayList<>(), result);
return result;
}
public void helper(int[] candidates, int offset, int target, List<Integer> tmp, List<List<Integer>> result) {
if (target < 0) {
return;
}
if (target == 0) {
result.add(new ArrayList<Integer>(tmp));
return;
}
for (int i = offset; i < candidates.length; i++) {
if (i > offset && candidates[i] == candidates[i-1]) {
continue;
}
tmp.add(candidates[i]);
helper(candidates, i + 1, target - candidates[i], tmp, result);
tmp.remove(tmp.size() - 1);
}
}
}
标签:
原文地址:http://www.cnblogs.com/shini/p/4553656.html