Leetcode第40题:Combination Sum2(java实现)

本文深入探讨了一种解决组合总和问题的算法实现,通过使用递归搜索和回溯技术,有效地找到所有可能的候选数集合,这些集合的元素之和等于目标值。文章详细解释了代码逻辑,包括如何避免重复解决方案,以及如何通过排序和条件判断来优化搜索过程。

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

题目描述:

题目解答:

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> outcome=new ArrayList<>();
        List<Integer> currentList=new ArrayList<>();
        searchSet(candidates,target,0,outcome,currentList);
        return outcome;
    }
    public void searchSet(int[] candidates,int target,int currentIndex,List<List<Integer>> outcome,List<Integer> currentList){
        if(target==0){
            outcome.add(new ArrayList<Integer>(currentList));
        }else if(target>0){
            for(int i=currentIndex;i<candidates.length;i++){
                //如果出现有数字和前面的一样就跳过,因为在下面的迭代中已经完成添加了,为了防止重复
                if(i>currentIndex&&candidates[i]==candidates[i-1]){
                    continue;
                }                    
                currentList.add(candidates[i]);                                        
                searchSet(candidates,target-candidates[i],i+1,outcome,currentList);
                currentList.remove(currentList.size()-1);
                    
            }
        }
    }
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值