我们社区陆续会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。
LeetCode 算法到目前我们已经更新了 39 期,我们会保持更新时间和进度(周一、周三、周五早上 9:00 发布),每期的内容不多,我们希望大家可以在上班路上阅读,长久积累会有很大提升。
不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。
难度水平:中等
给定一个候选人编号的集合 candidates
和一个目标数 target
,找出 candidates
中所有可以使数字和为 target
的组合。
candidates
中的每个数字在每个组合中只能使用 一次 。
注意: 解集不能包含重复的组合。
示例 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
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()}}}
该算法题解的仓库:LeetCode-Swift
点击前往 LeetCode 练习
我们是由 Swift 爱好者共同维护,我们会分享以 Swift 实战、SwiftUI、Swift 基础为核心的技术内容,也整理收集优秀的学习资料。
后续还会翻译大量资料到我们公众号,有感兴趣的朋友,可以加入我们。
Copyright © 2023 leiyu.cn. All Rights Reserved. 磊宇云计算 版权所有 许可证编号:B1-20233142/B2-20230630 山东磊宇云计算有限公司 鲁ICP备2020045424号
磊宇云计算致力于以最 “绿色节能” 的方式,让每一位上云的客户成为全球绿色节能和降低碳排放的贡献者