【LeetCode】 40. Combination Sum II 组合总和 II(Medium)(JAVA)
题目地址: https://leetcode.com/problems/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:
1. All numbers (including target) will be positive integers.
2. 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]
]
题目大意
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
说明:
1. 所有数字(包括目标数)都是正整数。
2. 解集不能包含重复的组合。
解题方法
这道题比【LeetCode】 39. Combination Sum 组合总和(Medium)(JAVA) 就多了两个条件:
1、数组元素不能重复使用
2、数组里包含重复元素
所以解法也类似,只是多了一些过滤;为了防止重复,开始位置也要往后移一位
1、if (i > index && nums[i] == nums[i - 1]) continue;
2、cH(nums, target - nums[i], i + 1);
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> cur = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
cH(candidates, target, 0);
return res;
}
public void cH(int[] nums, int target, int index) {
if (target < 0) return;
if (target == 0) {
res.add(new ArrayList<>(cur));
return;
}
for (int i = index; i < nums.length; i++) {
if (i > index && nums[i] == nums[i - 1]) continue;
if (nums[i] > target) break;
cur.add(nums[i]);
cH(nums, target - nums[i], i + 1);
cur.remove(cur.size() - 1);
}
}
}
执行用时 : 2 ms, 在所有 Java 提交中击败了 100.00% 的用户
内存消耗 : 39.4 MB, 在所有 Java 提交中击败了 21.87% 的用户