题目描述
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:“23”
输出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
题解:
深度优先搜索
def DFS(idx, lst, tmp, res):
if idx==len(lst):
res.append(tmp)
return res
for j in range(len(lst[idx])):
tmp += lst[idx][j]
DFS(idx+1, lst, tmp, res)
tmp = tmp[:-1]
class Solution(object):
def letterCombinations(self, digits):
if digits=="":
return []
lst, res = [], []
for i in digits:
if i=='2':
lst.append('abc')
elif i=='3':
lst.append('def')
elif i=='4':
lst.append('ghi')
elif i=='5':
lst.append('jkl')
elif i=='6':
lst.append('mno')
elif i=='7':
lst.append('pqrs')
elif i=='8':
lst.append('tuv')
elif i=='9':
lst.append('wxyz')
for i in range(len(lst[0])):
tmp = lst[0][i]
DFS(1, lst, tmp, res)
return res