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);
        }
    }
}
相关推荐
fail_to_code33 分钟前
递归法的递归函数何时需要返回值
算法
C137的本贾尼44 分钟前
(每日一道算法题)二叉树剪枝
算法·机器学习·剪枝
前端小崔1 小时前
前端面试题之ES6保姆级教程
开发语言·前端·javascript·面试·职场和发展·ecmascript·es6
BUG收容所所长2 小时前
栈的奇妙世界:从冰棒到算法的华丽转身
前端·javascript·算法
XRZaaa2 小时前
常见排序算法详解与C语言实现
c语言·算法·排序算法
@我漫长的孤独流浪2 小时前
数据结构测试模拟题(4)
数据结构·c++·算法
智驱力人工智能3 小时前
智慧零售管理中的客流统计与属性分析
人工智能·算法·边缘计算·零售·智慧零售·聚众识别·人员计数
WindSearcher4 小时前
大模型微调相关知识
后端·算法
取酒鱼食--【余九】4 小时前
rl_sar实现sim2real的整体思路
人工智能·笔记·算法·rl_sar
Magnum Lehar5 小时前
vulkan游戏引擎test_manager实现
java·算法·游戏引擎