面试算法-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();
        }
    }
}
相关推荐
顶点多余37 分钟前
那些在算法中适合巩固的知识点---1
java·前端·算法
罗西的思考2 小时前
【Agentic RL / 强化学习框架】Molt 设计解读
人工智能·算法·机器学习
黄敬峰2 小时前
Next.js 全栈实战:数据清洗、ORM 设计与 AI Prompt 工程最佳实践
面试·github
hahaha60163 小时前
HLS高层次综合设计技巧--C++类和模板
图像处理·人工智能·算法·计算机视觉
多弗朗皮卡丘4 小时前
算法详解4:买卖股票的最佳时机系列(上)
算法
维克兜率天6 小时前
【维克】动量指标家族:RSI、ROC、CCI、Momentum全面解析
python·算法
雨夜之寂6 小时前
雨夜-现在有办法识别是不是ai文章么
后端·面试
AI情绪识别开源7 小时前
检信 AI 智能推广平台(代号:JX-Promote)
人工智能·算法·erlang
老当益壮梁奶奶7 小时前
Linux软件编程学习笔记(八):进程间通信详解(1)
linux·c语言·笔记·学习·算法
不会就选b7 小时前
算法日常・每日刷题--<BFS拓扑排序>4
算法