前言
我們社區陸續會將顧毅(Netflix 增長黑客,《iOS 面試之道》作者,ACE 職業健身教練。微博:@故胤道長[1])的 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[2]
點擊前往 LeetCode[3] 練習
參考資料
[1]@故胤道長:
https://m.weibo.cn/u/1827884772
[2]LeetCode-Swift:
https://github.com/soapyigu/LeetCode-Swift[3]LeetCode: https://leetcode.com/problems/letter-combinations-of-a-phone-number
原文鏈接:https://mp.weixin.qq.com/s/aW5mrzeVnlHimQ6LkOe7Eg