1.递归
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'],
}
# 存储结果的数组
ret_str = []
if len(digits) == 0: return []
# 递归出口,当递归到最后一个数的时候result拿到结果进行for循环遍历
if len(digits) == 1:
return dic[int(digits[0])]
# 递归调用
result = self.letterCombinations(digits[1:])
# result是一个数组列表,遍历后字符串操作,加入列表
for r in result:
for j in dic[int(digits[0])]:
ret_str.append(j + r)
return ret_str
if __name__ == '__main__':
s = Solution()
print(s.letterCombinations('23'))
---------------------
作者:华软小白
来源:CSDN
原文:https://blog.csdn.net/chenhua1125/article/details/80554517
版权声明:本文为博主原创文章,转载请附上博文链接
2.DFS
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
dic = {'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
if digits == '':#排除为空的情况
return []
m = len(digits)
words = []
for elem in digits:#将数字解析为字母
words.append(dic[elem])
result = []#保存最后结果
strs = [0] * m#用来保存字母元素
stack = []#栈
stack.append([0,0])
while stack != []:
i,j = stack.pop()#出栈
strs[i] = words[i][j]
if i == m-1:#到达叶子节点,保存结果
result.append(''.join(strs))
if j < len(words[i])-1:#同一个index下,将当前元素右边元素入栈
stack.append([i,j + 1])
if i < m-1:#将下一个index的最左边的元素入栈
stack.append([i+1,0])
return result
3.迭代
class Solution:
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
num={
'2':'abc',
'3':'def',
'4':'ghi',
'5':'jkl',
'6':'mno',
'7':'pqrs',
'8':'tuv',
'9':'wxyz'
}
if len(digits)==0:
return []
res=['']
for i in range(len(digits)):
dlist=list(num[digits[i]])
new_res=[]
for j in range(len(res)):
for k in range(len(dlist)):
new_res.append(res[j]+dlist[k])
del res[:]
res=new_res.copy()
return res