17. Letter Combinations of a Phone Numbergit
Medium数组
Given a string containing digits from
2-9
inclusive, return all possible letter combinations that the number could represent.缓存A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.bash
1
o-o_
2
abc
3
def
app
4
ghi_
5
jkl
6
mno
ui
7
pqrs
8
tuv
9
wxyz
spa
*
+___
0
___
#
↑__
code除了0的第一个“”之外的位置的“”是为了对齐cdn
![]()
Example:blog
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
大意是指要把输入的数字按照手机键盘的映射关系转成可能的字符串
虽然题目中给出输入数字在[2, 9]
,实测(2019-01-05)
0
和1
也有对应的映射关系
0 => " "
1 => "*"
复制代码
基本分析:
n
的结果,首先要求长度为n-1
的结果!"0" : [" "],
"1" : ["*"],
"2" : ["a", "b", "c"],
"3" : ["d", "e", "f"],
"4" : ["g", "h", "i"],
"5" : ["j", "k", "l"],
"6" : ["m", "n", "o"],
"7" : ["p", "q", "r", "s"],
"8" : ["t", "u", "v"],
"9" : ["w", "x", "y", "z"]
复制代码
func letterCombinations(s: String) -> [String] {
if s 为空字符串, return 空数组
if cache 不包含 s {
cache[s] = cache[s的第一个字符] * letterCombinations(s除了第一字符之外剩下的部分的结果)
}
return cache[s]
}
复制代码
// Swift Code
class Solution {
var cache: [String : [String]] = [
"0" : [" "],
"1" : ["*"],
"2" : ["a", "b", "c"],
"3" : ["d", "e", "f"],
"4" : ["g", "h", "i"],
"5" : ["j", "k", "l"],
"6" : ["m", "n", "o"],
"7" : ["p", "q", "r", "s"],
"8" : ["t", "u", "v"],
"9" : ["w", "x", "y", "z"]
]
func letterCombinations(_ digits: String) -> [String] {
if digits.isEmpty { return [] }
if !cache.keys.contains(digits) {
cache[digits] = letterCombinations(String(digits.prefix(1))).flatMap({ (s) -> [String] in
letterCombinations(String(digits.suffix(digits.count - 1))).map { s + $0 }
})
}
return cache[digits]!
}
}
复制代码