码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 40. Combination Sum II

时间:2020-05-31 12:43:12      阅读:52      评论:0      收藏:0      [点我收藏+]

标签:重复   nbsp   input   数字   arrays   实现   ber   arraylist   can   

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]
]

组合总和II。跟版本一类似,唯一不同的地方在于input里面是有重复数字的。那么这个题就需要排序了,同时helper函数中需要skip掉重复的数字,其余思路跟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 题目总结

[LeetCode] 40. Combination Sum II

标签:重复   nbsp   input   数字   arrays   实现   ber   arraylist   can   

原文地址:https://www.cnblogs.com/cnoodle/p/12996797.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!