Combination Sum I and II

本文介绍了一种使用递归辅助函数解决组合求和问题的方法。通过实现特定的helper函数,文章详细展示了如何寻找所有可能的组合来达到目标值。代码中运用了回溯的思想,并考虑了重复元素的情况。

比较典型的helper的题目,现在我还搞不太清楚dfs之类的,只能用helper来统称了,你明白那个调调就行

public class Solution {
    public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
        ArrayList<ArrayList<Integer>> res =new ArrayList<ArrayList<Integer>>();
        Arrays.sort(candidates);
        if(candidates == null || candidates.length<1) return res;
        helper( candidates, target, res, new ArrayList<Integer>(), 0);
        return res;
    }
    public void helper(int[] c, int t,ArrayList<ArrayList<Integer>> res, ArrayList<Integer> item, int start ){
        if(0==t){
             res.add(new ArrayList<Integer> (item));//res.add(item);
            return; // 提速
        }
        if(0>t) return;
        for(int i=start; i< c.length; i++){
            if(i>start && c[i-1]==c[i]) continue;
            item.add(c[i]);
            helper(c, t-c[i], res, item, i); // 如果i变成i+1,则是不允许重复元素出现,而i,并且循环从i=start开始,则允许了重复元素构建target的可能性,一并解决了II
            item.remove(item.size()-1);
        }
    }
}

 

转载于:https://www.cnblogs.com/jiajiaxingxing/p/4423899.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值