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"].
这是一道排列组合的题,例子是求[a,b,c]和[d,e,f]的排列组合,有两种方法,一种是递归用DFS做
DFS需要有一个tmp来记录临时结果,用一个index来记录递归到了哪一层,跳出递归条件是递归到最后一层。
class Solution:
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
num_to_letters = {
'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"]
}
res=[]
tmp=''
self.dfs(digits,res,tmp,num_to_letters,0)
print(res)
def dfs(self,digits,res,tmp,letters,index):
if index==len(digits):
res.append(tmp)
return
for i in letters[digits[index]]:
self.dfs(digits,res,tmp+i,letters,index+1)
还有一种iteration迭代的方法,注意迭代不是简单的嵌套for循环,iteration用了两个数组,一个pre记录之前结果,一个now记录当前结果。首先把第一个数的字母放到now中,然后从第二个数开始遍历,将当前数字对应的字母加入pre中的每一项,如果以23为例的话,每一步的now如下,开始是['a','b','c']
['ad', 'bd', 'cd']
['ad', 'bd', 'cd', 'ae', 'be', 'ce']
['ad', 'bd', 'cd', 'ae', 'be', 'ce', 'af', 'bf', 'cf']
class Solution:
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
num_to_letters = {
'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"]
}
if not digits:
return []
nowlist = num_to_letters[digits[0]]
prelist = []
for digit in digits[1:]:
prelist = nowlist
nowlist = []
for letter in num_to_letters[digit]:
nowlist += [x + letter for x in prelist]
print(nowlist)
return nowlist