LeetCode0040组合总和 II

上篇博文我们解决了组合总和的问题
LeetCode0039组合总和
现在我们来看第40题

题目描述

在这里插入图片描述
在这里插入图片描述
这道题与上一问的区别在于:

第 39 题:candidates 中的数字可以无限制重复被选取。
第 40 题:candidates 中的每个数字在每个组合中只能使用一次。

编码的不同就在于,下一层递归的起始索引不一样。

第 39 题:还从候选数组的当前索引值开始。
第 40 题:从候选数组的当前索引值的下一位开始。

相同之处:解集不能包含重复的组合。

为了使得解集不包含重复的组合。我们想一想,如何去掉一个数组中重复的元素,除了使用哈希表以外,我们还可以先对数组升序排序,重复的元素一定不是排好序以后的 1 个元素和相同元素的第 1 个元素。根据这个思想,我们先对数组升序排序是有必要的。候选数组有序,对于在递归树中发现重复分支,进而“剪枝”是十分有效的。

Java代码

class Solution {
    private void findCombinationSum2(int[] candidates,int begin,int len,
    int residue,Stack<Integer> stack,List<List<Integer>> res){
        if(residue==0){
            res.add(new ArrayList<>(stack));
            return;
        }
        for(int i=begin;i<len&&residue-candidates[i]>=0;i++){
            if(i>begin&&candidates[i]==candidates[i-1]){
                continue;
            }
            stack.add(candidates[i]);
            findCombinationSum2(candidates,i+1,len,
            residue-candidates[i],stack,res);
            stack.pop();
        }
    }
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        int len=candidates.length;
        List<List<Integer>> res=new ArrayList<>();
        if(len==0){
            return res;
        }
        Arrays.sort(candidates);
        findCombinationSum2(candidates,0,len,target,new Stack<>(),res);
        return res;
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值