40. Combination Sum II

本文深入探讨了组合求和算法的实现,通过两个不同的方法展示了如何从候选数中找到所有可能的组合,使得这些组合的元素之和等于目标值。算法首先对候选数进行排序,然后使用递归方式生成所有可能的组合,同时避免重复组合的产生。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> ret=new ArrayList<List<Integer>>();
        Arrays.sort(candidates);
        boolean[] used=new boolean[candidates.length];
        generateCombination(new ArrayList<Integer>(), 0, target, used, ret, candidates);
        return ret;
    }
    private void generateCombination(List<Integer> list, int idx, int target, boolean[] used, List<List<Integer>> combs, int[] candidates){
        if(target==0)
        {
            combs.add(new ArrayList<Integer>(list));
            return;
        }
        if(idx>=candidates.length||target<0)
            return;
        generateCombination(list, idx+1, target, used, combs, candidates);
        if(idx>0&&used[idx-1]==false&&candidates[idx-1]==candidates[idx])
            return;
        list.add(candidates[idx]);
        used[idx]=true;
        generateCombination(list, idx+1, target-candidates[idx], used, combs, candidates);
        list.remove(list.size()-1);
        used[idx]=false;
    }
}

 

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> combs=new ArrayList<List<Integer>>();
        Arrays.sort(candidates);
        generateCombination(new ArrayList<Integer>(), 0, target, combs, candidates);
        return combs;
    }
    private void generateCombination(List<Integer> list, int idx, int target, List<List<Integer>> combs, int[] candidates){
        if(target==0)
        {
            combs.add(new ArrayList<Integer>(list));
            return;
        }
        if(idx>=candidates.length||target<0)
            return;
        for(int i=idx;i<candidates.length;i++)
        {
            if(i>idx&&candidates[i]==candidates[i-1])
                continue;
            list.add(candidates[i]);
            generateCombination(list, i+1, target-candidates[i], combs, candidates);
            list.remove(list.size()-1);
        }
    }
}

 

转载于:https://www.cnblogs.com/asuran/p/7584720.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值