[LeetCode] 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 sum to target.

Each number in candidates may only be used once in the combination.

Note: The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8
Output: 
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5
Output: 
[
[1,2,2],
[5]
]

Constraints:

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

组合总和 II。

给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用 一次 。

注意:解集不能包含重复的组合。 

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/combination-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

跟版本一类似,不同的地方在于

  • input 里面是有重复数字的
  • 结果集不能有重复的结果
  • 每个数字只能用一次

那么这个题就需要排序了,排序的目的是易于发现重复的数字,因为重复的数字是相邻的(21行)。

同时注意25行为什么 start + 1 是因为每个数字只能用一次。其余思路跟39题没有任何区别。

时间O(2^n)

空间O(n)

Java实现

 1 class Solution {
 2     public List<List<Integer>> combinationSum2(int[] candidates, int target) {
 3         List<List<Integer>> res = new ArrayList<>();
 4         if (candidates == null || candidates.length == 0) {
 5             return res;
 6         }
 7         Arrays.sort(candidates);
 8         helper(res, new ArrayList<>(), candidates, target, 0);
 9         return res;
10     }
11 
12     private void helper(List<List<Integer>> res, List<Integer> list, int[] candidates, int target, int start) {
13         if (target < 0) {
14             return;
15         }
16         if (target == 0) {
17             res.add(new ArrayList<>(list));
18             return;
19         }
20         for (int i = start; i < candidates.length; i++) {
21             if (i != start && candidates[i] == candidates[i - 1]) {
22                 continue;
23             }
24             list.add(candidates[i]);
25             helper(res, list, candidates, target - candidates[i], i + 1);
26             list.remove(list.size() - 1);
27         }
28     }
29 }

 

LeetCode 题目总结

posted @ 2020-05-31 11:16  CNoodle  阅读(460)  评论(0编辑  收藏  举报