40. Combination Sum II

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:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.

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

Solution:Backtracking

总结见:http://www.jianshu.com/p/883fdda93a66
思路:
和39题 Combination Sum http://www.jianshu.com/p/65dbdddcd398 思路相同,加上 if(i > start && nums[i] == nums[i - 1]) continue; to skip duplicates (sort 是必需的)
Time Complexity: O(2^N) Space Complexity: O(N)

Solution Code:

class Solution {
    public List<List<Integer>> combinationSum2(int[] nums, int target) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> cur_res = new ArrayList<>();
        Arrays.sort(nums);
        backtrack(nums, 0, target, cur_res, result);
        return result;
    }

    private void backtrack(int[] nums, int start, int remain, List<Integer> cur_res, List<List<Integer>> result) {
        if(remain < 0) return; // early stop
        else if(remain == 0) {
            result.add(new ArrayList<>(cur_res));
        }
        else{
            for(int i = start; i < nums.length; i++){
                if(i > start && nums[i] == nums[i - 1]) continue; // skip duplicates
                cur_res.add(nums[i]);
                backtrack(nums, i + 1, remain - nums[i], cur_res, result);
                cur_res.remove(cur_res.size() - 1); 
            }
        }
    } 
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,776评论 0 33
  • Given a collection of candidate numbers (C) and a target ...
    Jeanz阅读 385评论 0 0
  • 宝贝,爸爸希望你健康长大,你的小手抓着爸爸的食指,温暖,有力量。 宝贝,爸爸希望你做一个安静的美男子,不役于物,也...
    任浩阅读 380评论 0 0
  • 01 小表弟不见了。 半夜,舅妈的一个电话让我们全家都出动了,沿着漆黑的乡村土路四处寻找,凡是能想到的地方都去找了...
    米汤泡米饭汤慧阅读 413评论 0 1
  • 我们都是水中鱼 我们都是天上鸟 我们都是离离原上草。 我们是鱼 水中毋庸置疑的健将 却要钻出水面寻找呼吸的氧气; ...
    碧波飞龙阅读 290评论 6 1