【leetcode】39. 组合总和(java实现)

本文通过一个具体的代码示例,详细解析了如何使用回溯法解决组合总和问题,即寻找候选数列表中所有可能的组合,使得组合之和等于目标值。文章深入浅出地解释了递归过程,并通过调试打印帮助读者理解每一步操作。

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

示例:

输入: candidates = [2,3,5], target = 8,
所求解集为:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

这道题我没解出来,但是看了大神的代码瞬间神清气爽:

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> listAll=new ArrayList<List<Integer>>();
        List<Integer> list=new ArrayList<Integer>();
        //排序
        Arrays.sort(candidates);
        find(listAll,list,candidates,target,0);
        return listAll;
    }
    public void find(List<List<Integer>> listAll,List<Integer> tmp,int[] candidates, int target,int num){
        //递归的终点
        if(target==0){
            listAll.add(tmp);
            return;
        } 
        if(target<candidates[0]) return;
        for(int i=num;i<candidates.length&&candidates[i]<=target;i++){
            //深拷贝
            List<Integer> list=new ArrayList<>(tmp);
            list.add(candidates[i]);
            //递归运算,将i传递至下一次运算是为了避免结果重复。
            find(listAll,list,candidates,target-candidates[i],i);
        }   
    } 
}

这个递归其实就是回溯法,不懂回溯法的童鞋请看这篇文章:java实现回溯算法

为了更简单的理解这段代码,在

list.add(candidates[i]);

下面添加这段代码进行调试打印System.out.println(i+":"+list);

运行代码可以看到:

输入:

[2,3,6,7]
7

stdout:

0:[2]
0:[2, 2]
0:[2, 2, 2]
1:[2, 2, 3]
1:[2, 3]
1:[3]
1:[3, 3]
2:[6]
3:[7]

很奇怪为什么没有[2, 2, 6],[2, 2, 7]之类的勒,其实是被这个for循环的限制条件candidates[i]<=target给限制掉了,因为每次的target都是不一样的,这样的好处就减少了递归的成本,不用每个排列都一一进行比较。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值