leetcode-mid-backtracking-17. Letter Combinations of a Phone Number
阅读原文时间:2023年07月12日阅读:1

mycode  68.26%

class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if digits == "":
return []
dict = {'':['a','b','c'],
'':['d','e','f'],
'':['g','h','i'],
'':['j','k','l'],
'':['m','n','o'],
'':['p','q','r','s'],
'':['t','u','v'],
'':['w','x','y','z']
}
def dfs(index,temp):
if index==self.len:
self.res.append(temp)
return
num = digits[index]
s = dict[num]
for i in s:
dfs(index+1,temp+i)
self.res = []
self.len = len(digits)
dfs(0,"")
return self.res

参考:

def letterCombinations(digits):
def dfs(num, string):
if num == length:
res.append(string)
return
for letter in dict[digits[num]]:
dfs(num+1, string+letter)

    dict = {'':\['a','b','c'\],  
            '':\['d','e','f'\],  
            '':\['g','h','i'\],  
            '':\['j','k','l'\],  
            '':\['m','n','o'\],  
            '':\['p','q','r','s'\],  
            '':\['t','u','v'\],  
            '':\['w','x','y','z'\]  
            }  
    res = \[\]  
    length = len(digits)  
    dfs(0, '')  
    return res