leetcode_middle_64_39. Combination Sum

题意:

给出一列不重复的数字,从中选取一组数字,其和为目标数(每个数可以选取0到无穷次),返回所有可能的组合。


分析:

这是一道搜索题,先画出搜索树。

     2                3                  6              7

2  3  6 7      2 3  6 7      2 3 6 7     2 3 6 7

递归深搜,每层范围是数组全部,结束条件是等于大于和,满足条件是等于和。

然后写出来发现搜索树写错了,因为不同顺序算一种,所以多设置一个参数s,每次只遍历自己之后的:

public class Solution {
    List<Integer> l = null;
    List<List<Integer>> list = null;
    int target = 0;
    int[] candidates;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        l = new ArrayList<>();
        list = new ArrayList<>();
        this.target = target;
        this.candidates = candidates;
        
        for(int i=0; i<candidates.length; i++){
            l.add(candidates[i]);
            helper(i, candidates[i]);
            l.remove(l.size()-1);
        }
        return list;
    }
    
    private void helper(int s, int sum){
        if(sum >= target){
            if(target == sum){
                list.add(new ArrayList(l));
            }
            return;
        }
        
        for(int i=s; i<candidates.length; i++){
            l.add(candidates[i]);
            helper(i, sum+candidates[i]);
            l.remove(l.size()-1);
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值