Description
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.
Example
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
题目大意
像九宫格的按键一样, 一个数字对应一字符串,按不同的数字能得到对应的字母组合
解题思路
如示例’23’, ‘2’对应’abc’,‘3’对应’def’
第一层’2’得到’a’,‘b’,‘c’
第二层在’2’的基础’a’,‘b’,‘c’上分别加上’d’,‘e’,‘f’
首先’a’ + ‘d’,‘e’,‘f’ = ‘ad’,‘ae’,‘af’
再看’b’ + ‘d’,‘e’,‘f’ = ‘bd’,‘be’,‘bf’
最后’c’ + ‘d’,‘e’,‘f’ = ‘cd’,‘ce’,‘cf’
如果’234’, 在’23’基础上加上’4’对应的’g’,‘h’,i’
所以
‘ad’,‘ae’,‘af’ + ‘g’ = ‘adg’,‘aeg’,‘afg’
‘ad’,‘ae’,‘af’ + ‘h’ = ‘adh’,‘aeh’,‘afh’
‘ad’,‘ae’,‘af’ + ‘i’ = ‘adi’,‘aei’,‘afi’
所以递归就能实现了
code
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
self.dic=['','1','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']
if len(digits) == 0:
return []
res = ['']
for digit in digits:
res = self.Combinations(int(digit), res)
return res
def Combinations(self, digit, res):
return [i+j for i in res for j in self.dic[digit]]
Runtime:36ms
参考较优解
code
class Solution:
keymap = {
2: "abc",
3: "def",
4: "ghi",
5: "jkl",
6: "mno",
7: "pqrs",
8: "tuv",
9: "wxyz"
}
res = []
digits = ""
def buildletters(self, i, tmpstr):
if i == len(self.digits):
if tmpstr:
self.res.append(tmpstr)
return
for c in self.keymap[int(self.digits[i])]:
self.buildletters(i+1, tmpstr+c)
def letterCombinations(self, digits: str) -> List[str]:
self.res = []
self.digits = digits
self.buildletters(0, "")
return self.res
Runtime:28ms