面试算法-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();
        }
    }
}
相关推荐
折哥的程序人生 · 物流技术专研2 小时前
Java面试85题图解版 · 特别篇:2026后端高频面试题复盘(算法底层逻辑+高并发架构设计全解析,附Java实战代码)
java·网络·数据库·算法·面试
程序员二叉3 小时前
【Java】 异常高频面试题精讲 | 易错点+对比总结
java·开发语言·面试
想吃火锅10053 小时前
【leetcode】14.最长公共前缀js
算法·leetcode·职场和发展
云絮.4 小时前
数据库操作
数据库·mysql·算法·oracle
小林ixn5 小时前
LeetCode 206. 反转链表(迭代 + 递归详解)
算法·leetcode·链表
凡人叶枫5 小时前
Effective C++ 条款17:以独立语句将 newed 对象置入智能指针
java·linux·开发语言·c++·算法
我爱cope6 小时前
【Agent智能体26 | 多智能体-多智能体工作流】
人工智能·设计模式·语言模型·职场和发展
菜鸟‍6 小时前
LeetCode 1 27 和 704 || 两数之和 移除元素 二分查找
算法·leetcode·职场和发展
weixin_523185326 小时前
Java面试高频题:Integer缓存机制与 equals、== 区别
java·缓存·面试
退休倒计时7 小时前
【每日一题】LeetCode 142. 环形链表 II TypeScript
算法·leetcode·链表·typescript