美文网首页LeetCodeSwift 集
LeetCode - #40 组合总和 II

LeetCode - #40 组合总和 II

作者: Swift社区 | 来源:发表于2022-04-12 07:50 被阅读0次

    前言

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

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

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

    难度水平:中等

    1. 描述

    给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

    candidates 中的每个数字在每个组合中只能使用 一次

    注意: 解集不能包含重复的组合。

    2. 示例

    示例 1

    输入: candidates = [10,1,2,7,6,1,5], target = 8,
    输出:
    [
    [1,1,6],
    [1,2,5],
    [1,7],
    [2,6]
    ]
    

    示例 2

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

    约束条件:

    • 1 <= candidates.length <= 100
    • 1 <= candidates[i] <= 50
    • 1 <= target <= 30

    3. 答案

    class CombinationSumII {
        func combinationSum2(candidates: [Int], _ target: Int) -> [[Int]] {
            var res = [[Int]](), path = [Int]()
            
            dfs(&res, &path, target, candidates.sorted(), 0)
            
            return res
        }
        
        fileprivate func dfs(_ res: inout [[Int]], _ path: inout [Int], _ target: Int, _ candidates: [Int], _ index: Int) {
            if target == 0 {
                res.append(Array(path))
                return
            }
            
            for i in index..<candidates.count {
                guard candidates[i] <= target else {
                    break
                }
                
                if i > 0 && candidates[i] == candidates[i - 1] && i != index {
                    continue
                }
                
                path.append(candidates[i])
                _dfs(&res, &path, target - candidates[i], candidates, i + 1)
                path.removeLast()
            }
        }
    }
    
    • 主要思想:经典的深度优先搜索。
    • 时间复杂度: O(n^n)
    • 空间复杂度: O(2^n - 2)

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

    点击前往 LeetCode 练习

    关于我们

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

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

    相关文章

      网友评论

        本文标题:LeetCode - #40 组合总和 II

        本文链接:https://www.haomeiwen.com/subject/acfadrtx.html