面试算法-115-组合总和

题目

给你一个 无重复元素 的整数数组 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 。

仅有这两种组合。

解

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

    public void dfs(int[] candidates, int index, int target, LinkedList<Integer> path, List<List<Integer>> result) {
        if (target == 0) {
            result.add(new LinkedList<>(path));
            return;
        }
        if (target < 0) {
            return;
        }

        for (int i = index; i < candidates.length; i++) {
            path.add(candidates[i]);
            dfs(candidates, i, target - candidates[i], path, result);
            path.removeLast();
        }
    }
}
相关推荐
Thanks_ks32 分钟前
常见 HTTP 状态码的坑:301/302、401/403、500/502 之间差的那一个词
计算机网络·nginx·http·面试·状态码·后端开发·浏览器缓存
怕浪猫33 分钟前
Super-agent 在各大模型厂商的应用情况
算法·面试·github
天真小巫34 分钟前
2026.11.1总结
职场和发展
海绵宝宝转agent1 小时前
LeetCode100 二叉树个人题解
算法·leetcode·深度优先
octopus_c1 小时前
C++ 模板详解:函数模板、类模板、特化与分离编译
开发语言·c++·算法
東隅已逝,桑榆非晚1 小时前
算法1. 双指针法-移动零
c++·算法
CQU_JIAKE2 小时前
11.1[A]
算法
滼2 小时前
AI 数据安全面试应答框架:从大框架到小点
大数据·人工智能·安全·面试·安全架构
小郎君6582 小时前
(六)el-cascader 的展示值为什么不能直接 join:emitPath、路径还原与多选去重
vue.js·算法
郝学胜-神的一滴4 小时前
游戏设计:原型与开发 19:U3D工位布置与性格说明书
人工智能·算法·unity·unreal engine·游戏策划·游戏设计