乐趣区

40. Combination Sum II

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.Each number in candidates may only be used once in the combination.Note:All numbers (including target) will be positive integers.The solution set must not contain duplicate combinations.Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]
]

难度:medium
题目:给定一无重复元素的集合和一指定数,找出所有由数组内元素之和为该数的序列。每个元素在组合中仅可被使用一次。注意:所以元素都为正整数包括给定的整数。答案不允许有重复的组合。
思路:递归
Runtime: 10 ms, faster than 84.44% of Java online submissions for Combination Sum II.Memory Usage: 31.5 MB, less than 6.01% of Java online submissions for Combination Sum II.
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> result = new ArrayList();
combinationSum(candidates, 0, target, 0, new Stack<>(), result);

return result;
}

private void combinationSum(int[] cs, int idx, int target, int s, Stack<Integer> stack, List<List<Integer>> r) {
if (s == target) {
r.add(new ArrayList(stack));
return;
}

for (int i = idx; i < cs.length; i++) {
if (s + cs[i] <= target && (i == idx || cs[i – 1] != cs[i])) {
stack.push(cs[i]);
combinationSum(cs, i + 1, target, s + cs[i], stack, r);
stack.pop();
}
}
}
}

退出移动版