LeetCode之電話號(hào)碼的字母組合
前言
我們社區(qū)陸續(xù)會(huì)將顧毅(Netflix 增長(zhǎng)黑客,《iOS 面試之道》作者,ACE 職業(yè)健身教練。微博:@故胤道長(zhǎng)[1])的 Swift 算法題題解整理為文字版以方便大家學(xué)習(xí)與閱讀。
LeetCode 算法到目前我們已經(jīng)更新了 16 期,我們會(huì)保持更新時(shí)間和進(jìn)度(周一、周三、周五早上 9:00 發(fā)布),每期的內(nèi)容不多,我們希望大家可以在上班路上閱讀,長(zhǎng)久積累會(huì)有很大提升。
不積跬步,無(wú)以至千里;不積小流,無(wú)以成江海,Swift社區(qū) 伴你前行。如果大家有建議和意見(jiàn)歡迎在文末留言,我們會(huì)盡力滿足大家的需求。
難度水平:中等
1. 描述
給定一個(gè)僅包含數(shù)字 2-9 的字符串,返回所有它能表示的字母組合。答案可以按 任意順序 返回。
給出數(shù)字到字母的映射如下(與電話按鍵相同)。注意 1 不對(duì)應(yīng)任何字母。
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'] 的一個(gè)數(shù)字
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]
- }
- }
- 主要思想:經(jīng)典的深度優(yōu)先搜索,首先創(chuàng)建電話板
- 時(shí)間復(fù)雜度:O(4^n), n 表示數(shù)字長(zhǎng)度
- 空間復(fù)雜度:O(n), n 表示數(shù)字長(zhǎng)度
該算法題解的倉(cāng)庫(kù):LeetCode-Swift[2]
點(diǎn)擊前往 LeetCode[3] 練習(xí)
參考資料
[1]@故胤道長(zhǎng):
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