题目:
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"].
本人代码:
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
dic = {"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']}
m = len(digits)
result = [] #记录最终结果
temp = [] #记录添加一组字母后的临时结果
for i in range(m) :
if len(result) > 0 :
for x in result :
for y in dic[digits[i]] :
temp.append(x+y)
else :
for y in dic[digits[i]] :
temp.append(y)
result = temp
temp = []
return result
其他大牛算法:
1、典型的回溯法
def letterCombinations(self, digits):
mapping = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',
'6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
if len(digits) == 0:
return []
if len(digits) == 1:
return list(mapping[digits[0]])
prev = self.letterCombinations(digits[:-1])
additional = mapping[digits[-1]]
return [s + c for s in prev for c in additional]
2、一行代码解决
if '' == digits: return []
kvmaps = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
}
return reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, [''])