39. 组合总和 - 力扣(LeetCode)

题目描述
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

输入示例

candidates = [2,3,6,7], target = 7

输出示例

[[2,2,3],[7]]

解释

23 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

解题思路
我们使用回溯、深度优先遍历的思想,比如我们按照示例,搜索 target 为 7,当我们开始搜索到 2 的时候,把 2 放入栈中然后搜索 target 为 5(因为7-2=5),由于存在重复组合,所以我们设置一个 begin,我们每次搜索都只能从 begin 开始搜索,比如我们 begin 到了搜索 3 的位置,我们就不会再使用前面的 2 了,这样可以去重复组合。由于我们只需要计算最后结果等于 0 的,而小于 0 的结果不需要记录,所以可以使用剪枝加速搜索。将候选数组排序,这是剪枝的前提,然后在搜索的第一步只需要判断等于0的情况进行记录,在遍历的时候将小于 0 的循环退出。
在这里插入图片描述

解题代码

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        int len = candidates.length;
        List<List<Integer>> res = new ArrayList<>();
        if(len == 0) {
            return res;
        }
        // 排序是剪枝的前提
        Arrays.sort(candidates);
        Deque<Integer> path = new ArrayDeque<>();
        backtrack(candidates, 0, len, target, path, res);
        return res;
    }

    public void backtrack(int[] candidates, int begin, int len, int target,
    Deque<Integer> path, List<List<Integer>> res) {
        // target为负数和0的时候不再产生新的孩子节点
        // 由于进入更深层的时候,小于0的部分被剪枝,因此递归终止条件值只判断等于0的情况
        if(target == 0) {
            res.add(new ArrayList<>(path));
            return;
        }
        // 从begin开始搜索
        for(int i = begin; i < len; i++) {
            // 重点理解这里剪枝,前提是候选数组已经有序
            if(target - candidates[i] < 0) {
                break;
            }
            // 添加
            path.addLast(candidates[i]);
            // 注意:由于每一个元素可以重复使用,下一轮搜索的起点依然是i,这里非常容易弄错
            backtrack(candidates, i, len, target-candidates[i], path, res);
            // 状态重置,回溯法一般都需要状态重置
            path.removeLast();
        }
    }
}
  • 15
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值