58、回溯-组合总和

思路:

数组内的每一个元素都可以无线使用只要最后可以拼接成target就可以。那么如何限制呢?

(target-已经拼接的和 )/当前元素  就是你可以利用的数量。代码如下:

class Solution {
    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans=new ArrayList<>();
        if (candidates==null||candidates.length==0){
            return ans;
        }
        Deque<Integer> path=new LinkedList<>();
        process(candidates,0,target,path,ans);
        return ans;
    }

    private static void process(int[] candidates, int index, int rest, Deque<Integer> path, List<List<Integer>> ans) {
        if (rest==0){
            ans.add(new ArrayList<>(path));
            return;
        }
        if (index==candidates.length){
            return;
        }
        int count=rest/candidates[index];
        for (int i = 0; i <=count; i++) {
            if (i!=0){
                path.addFirst(candidates[index]);
            }
            process(candidates,index+1,rest-candidates[index]*i,path,ans);
        }
        //移除path张数
        for (int i = 1; i <=count; i++) {
            path.removeFirst();
        }
    }
}

这里使用的双端队列,目的就是为了方便还原现场

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值