39.组合总和(回溯算法)

在这里插入图片描述

这道题与上一篇文章写的组合那道题极度的类似,链接在此79.组合(回溯)

那么这道题和上一道题的区别是什么呢

就是这道题是一个元组中要求可以有重复的元素,比如7,7是允许的。
而上一道题是不允许的。

也就说这道题递归不用从i+1 开始

在这里插入图片描述

和上一道题一样我们都要有个start索引来判断起始位置。
如果没有start就会又重复的元组
即:从每一层的第 2 个结点开始,都不能再搜索产生同一层结点已经使用过的 candidate 里的元素。
在这里插入图片描述

递归结束的终止条件就是,如果总和等于目标值或者总和大于了目标值。

class Solution {
   public  List<List<Integer>> res = new ArrayList<>();

    
    public  List<List<Integer>> combinationSum(int[] candidates, int target) {
        dfs(candidates,target,new ArrayList<>(),0,0);
        return res;
    }

    public  void dfs(int[] candidates,int target,List<Integer> path,int sum,int start){
        if(sum > target ){
            return;
        }
        if(sum == target){
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = start;i < candidates.length;i++){
            sum += candidates[i];
            path.add(candidates[i]);
            dfs(candidates,target,path,sum,i);
            sum -= candidates[i];
            path.remove(path.size() - 1);
        }
    }
}

剪枝优化

在这个树形结构中:
在这里插入图片描述

以及上面的版本一的代码大家可以看到,对于sum已经大于target的情况,其实是依然进入了下一层递归,只是下一层递归结束判断的时候,会判断sum > target的话就返回。

其实如果已经知道下一层的sum会大于target,就没有必要进入下一层递归了。

那么可以在for循环的搜索范围上做做文章了。

对总集合排序之后,如果下一层的sum(就是本层的 sum + candidates[i])已经大于target,就可以结束本轮for循环的遍历。

如图

在这里插入图片描述
剪枝代码

for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++)

总体代码

class Solution {
   public  List<List<Integer>> res = new ArrayList<>();

    
    public  List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        dfs(candidates,target,new ArrayList<>(),0,0);
        return res;
    }

    public  void dfs(int[] candidates,int target,List<Integer> path,int sum,int start){
        if(sum > target ){
            return;
        }
        if(sum == target){
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = start;i < candidates.length&& sum + candidates[i] <= target;i++){
            sum += candidates[i];
            path.add(candidates[i]);
            dfs(candidates,target,path,sum,i);
            sum -= candidates[i];
            path.remove(path.size() - 1);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值