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

思路:dfs

java 复制代码
class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        List<Integer> pair = new ArrayList<Integer>();
        dfs(candidates, target, ans, pair, 0);
        return ans;
    }

    public void dfs(int[] candidates, int target, List<List<Integer>> ans, List<Integer> pair, int idx) {
        if (idx == candidates.length) {
            return;
        }
        if (target == 0) {
            ans.add(new ArrayList<Integer>(pair));
            return;
        }
        // 直接跳过
        dfs(candidates, target, ans, pair, idx + 1);
        // 选择当前数
        if (target - candidates[idx] >= 0) {
            pair.add(candidates[idx]);
            dfs(candidates, target - candidates[idx], ans, pair, idx); // 可以重复选所以下标是idx
            pair.remove(pair.size() - 1);
        }
    }
}
相关推荐
Dream it possible!9 分钟前
LeetCode 面试经典 150_分治_合并 K 个升序链表(108_23_C++_困难)
c++·leetcode·链表·面试·分治
天赐学c语言10 分钟前
12.29 - 字符串相加 && vector和map的区别
数据结构·c++·算法·leecode
一招定胜负14 分钟前
支持向量机实现垃圾邮件分类及参数调优原理
算法·支持向量机·分类
CodeByV18 分钟前
【算法题】位运算
数据结构·算法
郝学胜-神的一滴25 分钟前
李航《机器学习方法》全面解析与高效学习指南
人工智能·python·算法·机器学习·数学建模·scikit-learn
CS创新实验室25 分钟前
奈奎斯特定理:信号处理与通信领域的基石理论
计算机网络·算法·信号处理·奈奎斯特定理
雪花desu29 分钟前
【Hot100-Java简单】/LeetCode 283. 移动零:两种 Java 高效解法详解
数据结构·python·算法
随意起个昵称30 分钟前
【做题总结】顺子(双指针)
c++·算法
一杯咖啡Miracle37 分钟前
UV管理python环境,打包项目为docker流程
python·算法·docker·容器·uv
玉树临风ives42 分钟前
atcoder ABC438 题解
数据结构·算法