#dfs(深度优先遍历)
#将数字转为字典格式
#定义dfs函数(本质上回溯问题),遍历dic[digit]返回值为dfs()函数,达到遍历的目的
#ps:由于存在空字符串的情况,必须设置加入条件!=''
def letterCombinations(self, digits: str) -> 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']}
res = []
def dfs(digits,temp):
if len(digits)==0:
if temp !='':
res.append(temp)
return
digit = digits[0]
for ch in dic[digit]:
dfs(digits[1:],temp+ch)
dfs(digits,'')
return res
#笛卡尔积
#python人狂喜嗨还害
#本质上为
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
conversion={'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
if len(digits)==0:
return []
product=['']
for k in digits:
product=[i+j for i in product for j in conversion[k]] # for i for j 然后返回列表i与j的所有组合
return product
# 探究i+j for i in a for j in b
a = ['a','b','c']
b = ['d','e']
res = [i+j for i in a for j in b]
res