LeetCode 39.组合总和

详情链接:Leetcode 139.组合总和

1.问题思路

组合和排列问题是经典的回溯题,依据递归三部曲

  1. 确定递归方法参数及返回值。

    public void dfs(int[] candidates, int target, int curr, int startIndex)
    
  2. 递归终止条件。

当curr > target已经超过了目标值,则不符合条件,需要进行回溯;
当curr = target满足条件,添加至结果集中。

这里注意一点点,数字可以无限制选取,所以每层的一个广度遍历是一致的,不需要过滤使用过的元素。
① 循环的退出条件,累加的数字等于targetNum则追加到结果集,如果大于targetNum则跳出当前层并进行回溯。
② 每层的循环遍历都是从【0, s.length-1】。

2.代码实现

class Solution {
    LinkedList<List<Integer>> result = new LinkedList<>();
    LinkedList<Integer> path = new LinkedList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        dfs(candidates, target, 0, 0);
        return result;
    }

    public void dfs(int[] candidates, int target, int curr, int startIndex) {
        // 终止条件
        if(curr > target) {
            return;
        }

        if(curr == target) {
            result.add(new ArrayList<>(path));
            return;
        }

        // 水平遍历
        for(int i=startIndex; i<candidates.length; i++) {
            int item = candidates[i];
            curr += item;
            path.add(item);
            dfs(candidates, target, curr, i);
            curr -= item;
            path.removeLast();
        }

    }
}
  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值