面试算法-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();
        }
    }
}
相关推荐
阿芯爱编程6 小时前
2025前端面试题
前端·面试
今天背单词了吗9807 小时前
算法学习笔记:19.牛顿迭代法——从原理到实战,涵盖 LeetCode 与考研 408 例题
笔记·学习·算法·牛顿迭代法
天真小巫7 小时前
2025.7.13总结
职场和发展
jdlxx_dongfangxing7 小时前
进制转换算法详解及应用
算法
倔强青铜三8 小时前
苦练Python第18天:Python异常处理锦囊
人工智能·python·面试
倔强青铜三8 小时前
苦练Python第17天:你必须掌握的Python内置函数
人工智能·python·面试
军军君018 小时前
基于Springboot+UniApp+Ai实现模拟面试小工具四:后端项目基础框架搭建下
spring boot·spring·面试·elementui·typescript·uni-app·mybatis
why技术8 小时前
也是出息了,业务代码里面也用上算法了。
java·后端·算法
2501_922895589 小时前
字符函数和字符串函数(下)- 暴力匹配算法
算法
IT信息技术学习圈10 小时前
算法核心知识复习:排序算法对比 + 递归与递推深度解析(根据GESP四级题目总结)
算法·排序算法