LeetCode39. 组合总和

problem

LeetCode39. 组合总和

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。

solution

思路过程

  • 回溯
  • 用Set来存储进行快速查找
  • 结束终点是sum 累加到了target

代码

class Solution {
    Set<Integer> set=new HashSet<>();
    int target;
    List<List<Integer>> res=new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        for(int candidate:candidates){
            set.add(candidate);
        }
        this.target=target;
        List<Integer> path=new ArrayList<>();
        combinationSumHelper(0,path);
        return res;

    }
    public void combinationSumHelper(int currSum,List<Integer> path){
        if(currSum==target){
            res.add(new ArrayList<>(path));
            return ;
        }
        for(int i=1;i<=target-currSum;++i){
            if(set.contains(i)){
                path.add(i);
                combinationSumHelper(currSum+i,path);
                path.remove(path.size()-1);
            }
        }
    }
}

分析
在这里插入图片描述

  • 这里,没有排除相同的组合,换句话说就是剪支,但是如何剪支呢?
  • 没想出来,看解答
  • 没看懂,回溯算法 + 剪枝(回溯经典例题详解)为每次遍历设置搜索的起点
  • 先抄一遍,看看以后能不能理解,也许没有以后了,╮(╯▽╰)╭
  • 没法想通,为什么设置一个搜索的起点,就可以没有相同的组合
  • 突然琢磨懂了,按照我的理解,就好像x+y=10,先从x开始,那么必定会出现y的结果,而下一个从y开始,就不能再把x弄进去,因为这个[x,y] 的序列和[y,x]的序列存在了。
  • 妈耶,我的脑子终开窍了

代码

class Solution {
    int target;
    List<List<Integer>> res=new ArrayList<>();
    int len=0;
    int [] candidates;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        this.target=target;
        this.len=candidates.length;
        this.candidates=candidates;
        List<Integer> path=new ArrayList<>();
        combinationSumHelper(target,path,0);
        return res;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值