leetcode 39. Combination Sum(组合数之和)

在这里插入图片描述
给出一个数组,每个数字都是不同的,返回所有的数字组合,使它们的和为target。
每个数字可以重复使用。

思路:
组合问题,用组合版的dfs,因为每个元素可以重复使用,所以下标从当前数字下标 i 开始
如下

dfs(start index, candidates):
  for i = i to end
    stack.push(candidates[i])
    dfs(i, candidates)
    stack.pop()

数字和为target,每经过一个元素,令剩下的元素和为target - candidates[i],直到target == 0,则满足和为target。
由于元素可重复使用,所以需要一个终止条件。当元素>target时,认为可以退出,进行下一元素。

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Stack<Integer> stack = new Stack<>();
        
        dfs(candidates, target, 0, stack, result);
        return result;
        
    }
    
    void dfs(int[] candidates, int target, int start, Stack<Integer> stack, List<List<Integer>> result) {
        if(target == 0) {
            result.add(new ArrayList<Integer>(stack));
            return;
        }
        
        for(int i = start; i < candidates.length; i ++) {
            if(candidates[i] > target) continue;
            stack.push(candidates[i]);
            dfs(candidates, target - candidates[i], i, stack, result);
            stack.pop();
        }
    }

也可以先把数组排序,当某个元素>target时,后面的必然更大,都不用看了,直接return。

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        
        int n = candidates.length;
        Stack<Integer> cur = new Stack<>();
        Arrays.sort(candidates);
        
        combination(candidates, 0, target, result, cur);
        return result;
    }
    
    public void combination(int[] candidates, int start, int target, List<List<Integer>> result, Stack<Integer> cur) {
        if(target < 0) {
            return;
        }
        if(target == 0) {
            result.add(new ArrayList<Integer>(cur));
            return;
        }
        
        for(int i = start; i < candidates.length; i++) {
            if(candidates[i] > target) {
                break;
            }
            cur.push(candidates[i]);
            combination(candidates, i, target - candidates[i], result, cur);
            cur.pop();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值