leetcode 39. 组合总和

题目链接
思路:深搜+回溯
分析:因为每个数字都可以用多次,也就是说要找到所有的可行解,那么这里使用的是搜索+回溯的方法来解决。
这里定义了dfs函数。
第一个参数是:排好序的candidates。
第二个参数是:当前需要凑出来的目标值。
第三个参数是:当前从candidates数字开始遍历的下标。
第四个参数是:candidates的长度。
dfs:函数功能是查找[index.n-1]范围内,能凑出tar的组合。

这里要注意,因为candidates中的元素都是正数,所以一旦最开始的元素就大于了tar,那么就可以直接跳出,就减枝了。

代码:

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> seqr = new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);

        dfs(candidates, target, 0, candidates.length);

        return  res;
    }

    //寻找出[index,n-1]的范围内能凑出tar的组合
    public void dfs(int[] candidates, int tar, int index, int n){
        if(tar==0){
            //目标为0,说明此时已经找到了组合
            //这里要注意,因为candidates中的元素都是整数,所以后面不会出现好几个数字相加为0的情况。
            //素以此时一旦满足了tar等于0,那么加入结果集后,直接返回    
            res.add(new ArrayList<>(seqr));
            return ;
        }

        if(candidates[index]>tar){
            return;
        }

        for(int i=index; i<n; i++){
            seqr.add(candidates[i]);
            dfs(candidates, tar-candidates[i], i, n);
            seqr.remove(seqr.size()-1);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值