【LeetCode】39.组合总和

组合总和

题目描述:

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

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

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

示例 1:

输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

示例 2:

输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]

示例 3:

输入: candidates = [2], target = 1
输出: []

提示:

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • candidates 的所有元素 互不相同
  • 1 <= target <= 40

思路分析:

        使用深度优先遍历 实现,使用一个列表,在 深度优先遍历 变化的过程中,遍历所有可能的列表并判断当前列表是否符合题目的要求。如果不符合进行剪枝。

说明:

  • 以 target = 7 为 根结点 ,创建一个分支的时 做减法 ;
  • 每一个箭头表示:从父亲结点的数值减去边上的数值,得到孩子结点的数值。边的值就是题目中给出的 candidate 数组的每个元素的值;
  • 减到 0或者负数的时候停止,即:结点 0和负数结点成为叶子结点;
  • 同时每一次搜索的时候设置 下一轮搜索的起点 begin,即:从每一层的第 222 个结点开始,都不能再搜索产生同一层结点已经使用过的 candidate 里的元素。

代码实现注解:

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        //定义一个返回结果的集合
        List<List<Integer>> res = new ArrayList<>();
        //定义一个表示数组的长度变量
        int len = candidates.length;
        if(len == 0)
            return res;
        //升序排序
        Arrays.sort(candidates);
        //定义一个存储树路径上的节点值的队列
        Deque<Integer> path = new ArrayDeque<>();
        //深度搜索,调用函数
        dfs(candidates, 0, len, target, path, res);
         return res;
    }
    private void dfs(int[] candidates, int begin, int len, int target, Deque<Integer> path,List<List<Integer>> res) {
        // 由于进入更深层的时候,小于 0 的部分被剪枝,因此递归终止条件值只判断等于 0 的情况
        if (target == 0) {
            //将节点值存入返回集合
            res.add(new ArrayList<>(path));
            return;
        }
        //begin用于记录当前遍历位置
        for (int i = begin; i < len; i++) {
            //剪枝操作,将叶子节点小于0的分支减掉
            if (target - candidates[i] < 0) {
                break;
            }
            path.addLast(candidates[i]);
            //将i传入可有效避免结果重复
            dfs(candidates, i, len, target - candidates[i], path, res);
            //回溯,移除path中最后一个元素
            path.removeLast();
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值