关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

LeetCode - #39 组合总和(Top 100)

发布时间:2023-06-29 17:01:02

前言

本题为 LeetCode 前 100 高频题

我们社区陆续会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。))的 Swift 算法题题解整理为文字版以方便大家学习与阅读。

LeetCode 算法到目前我们已经更新了 38 期,我们会保持更新时间和进度(周一、周三、周五早上 9:00 发布),每期的内容不多,我们希望大家可以在上班路上阅读,长久积累会有很大提升。

不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。

难度水平:中等

1. 描述

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

2. 示例

示例 1

输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

示例 2

输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]

示例 3

输入: candidates = [2], target = 1
输出: []

约束条件:

  • 1 <= candidates.length <= 30
  • 1 <= candidates[i] <= 200
  • candidate 中的每个元素都 互不相同
  • 1 <= target <= 500

3. 答案

class CombinationSum { func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] { var combination = [Int](), combinations = [[Int]]()dfs(candidates.sorted(), target, 0, &combinations, &combination)return combinations}private func dfs(_ candidates: [Int], _ target: Int, _ index: Int, _ combinations: inout [[Int]], _ combination: inout [Int]) { if target == 0 { combinations.append(combination)return}for i in index..<candidates.count { guard candidates[i] <= target else { break}combination.append(candidates[i])dfs(candidates, target - candidates[i], i, &combinations, &combination)combination.removeLast()}}}

  • 主要思想:经典的深度优先搜索。
  • 时间复杂度: O(n^n)
  • 空间复杂度: O(2^n - 1)

该算法题解的仓库:LeetCode-Swift

点击前往 LeetCode 练习

关于我们

我们是由 Swift 爱好者共同维护,我们会分享以 Swift 实战、SwiftUI、Swift 基础为核心的技术内容,也整理收集优秀的学习资料。

后续还会翻译大量资料到我们公众号,有感兴趣的朋友,可以加入我们。


/template/Home/leiyu/PC/Static