组合1.无重复元素

找出一个和为target的元素组合。元素可以重复使用
还是一样画出解空间树。这个和前面的区别就是选择列表少了很多,第二个数就不能选第一个数了,所以用一个begin可以标识出此时的列表 开始选择下标,这样在dfs的过程中传入了此时的i作为begin,也就是递归到下层时还是从此时的节点开始的,保证了选择列表中无法选择,而递归时可以选择。
还有就是此时的判断条件需要改变,因为现在不是到树的底部就结束,而是target到0结束,所以如果到了负数,则直接返回即可,因为再往下肯定大于target了。

class Solution {
    List<List<Integer>> res =new ArrayList<List<Integer>>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if(candidates.length==0){
            return res;
        }
        List<Integer> path=new ArrayList<>();
        core(candidates,target,0,path);
        return res;
    }
    public void core(int[] candidates,int target,int begin,List<Integer> path){
        if(target<0){
            return;
        }
        if(target==0){
            res.add(new ArrayList(path));
            return;
        }
        for(int i=begin;i<candidates.length;i++){
            path.add(candidates[i]);
            core(candidates,target-candidates[i],i,path);
            path.remove(path.size()-1);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值