关于我们

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

< 返回新闻公共列表

LeetCode - #17 电话号码的字母组合

发布时间:2023-06-28 19:00:19

前言

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

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

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

难度水平:中等

1. 描述

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

2. 示例

示例 1

输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]

示例 2

输入:digits = ""
输出:[]

示例 3

输入:digits = "2"
输出:["a","b","c"]

约束条件:

  • 0 <= digits.length <= 4
  • digits[i] 是范围 ['2', '9'] 的一个数字

3. 答案

class LetterCombinationsPhoneNumber { func letterCombinations(_ digits: String) -> [String] { guard digits.count > 0 else { return [String]()}var combinations = [String](), combination = ""let numberToStr = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]dfs(&combinations, &combination, numberToStr, digits, 0)return combinations}private func dfs(_ combinations: inout [String], _ combination: inout String, _ numberToStr: [String], _ digits: String, _ index: Int) { if combination.count == digits.count { combinations.append(combination)return}let currentStr = fetchCurrentStr(from: digits, at: index, numberToStr)for char in currentStr { combination.append(char)dfs(&combinations, &combination, numberToStr, digits, index + 1)combination.removeLast()}}private func fetchCurrentStr(from digits: String, at index: Int, _ numberToStr: [String]) -> String { guard index >= 0 && index < digits.count else { fatalError("Invalid index")}let currentDigitChar = digits[digits.index(digits.startIndex, offsetBy: index)]guard let currentDigit = Int(String(currentDigitChar)), currentDigit >= 0, currentDigit < numberToStr.count else { fatalError("Invalid digits")}return numberToStr[currentDigit]}}

  • 主要思想:经典的深度优先搜索,首先创建电话板
  • 时间复杂度: O(4^n), n 表示数字长度
  • 空间复杂度: O(n), n 表示数字长度

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

点击前往 LeetCode 练习

关于我们

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


/template/Home/leiyu/PC/Static