Given a digit string, 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.
Input:Digit string “23” Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
1 使用字典存储每个键代表的字母 2 获得输入的数字 3 迭代对输入的数字进行组合
class Solution(object):
def combine(self, str1, str2):
"""
:type str1: list[str]
:type str2: list[str]
:rtype: list[str]
"""
"""
对两个list进行合并,比如['a','b']和['d','e'合并为['ad','ae','bd','be']
"""
ret = []
if len(str1) == 0:
return str2
if len(str2) == 0:
return str1
for x in str1:
for y in str2:
ret.append(x+y)
return ret
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
ret = []
if len(digits) == 0:
return ret
dic = dict({'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'})
for x in digits:
str2 = list(dic[x])
ret = self.combine(ret,str2)
return ret