面试算法-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();
        }
    }
}
相关推荐
liujing102329292 分钟前
Day09_刷题niuke20250609
java·c++·算法
不7夜宵5 分钟前
力扣热题100 k个一组反转链表题解
算法·leetcode·链表
江城开朗的豌豆12 分钟前
JavaScript篇:偷懒也有理!事件代理让我少写一半代码
前端·javascript·面试
江城开朗的豌豆1 小时前
Proxy:JavaScript中的'变形金刚',让你的对象为所欲为!
前端·javascript·面试
江城开朗的豌豆1 小时前
JavaScript中的instanceof:你的代码真的认识'自家孩子'吗?
前端·javascript·面试
蒟蒻小袁1 小时前
力扣面试150题--课程表
算法·leetcode·面试
闻缺陷则喜何志丹1 小时前
【动态规划】B4336 [中山市赛 2023] 永别|普及+
c++·算法·动态规划·洛谷
张风捷特烈1 小时前
每日一题 Flutter#7,8 | 关于 State 两道简答题
android·flutter·面试
不二狗2 小时前
每日算法 -【Swift 算法】电话号码字母组合
开发语言·算法·swift
AL流云。2 小时前
【优选算法】分治
数据结构·算法·leetcode·排序算法