题目:
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
思路:
回溯,过程示例
a
ad
a
ae
a
af
a
b
bd
b
be
b
bf
b
c
cd
c
ce
c
cf
c
解答:
方法一:回溯
树的每层使用的是 不同的集合时,无需startidx
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"}
res=[]
path=[]
def tracebacking(digits,idx):
nonlocal res,path
if len(path)==len(digits):
res.append(''.join(path))
return
elements=digits[idx]
for c in dic[elements]:
path.append(c)
tracebacking(digits,idx+1)
path.pop()
if not digits:
return res
tracebacking(digits,0)
return res
原始解答:
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
result = []
if digits == "":
return result
#数字对应的英文字母列表
word_list = ["0", "0", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
#输入的digits的长度,作为回溯函数返回的判断条件
dlen = len(digits)
#回溯函数(path当前路径,默认为"")
def back_track(digits, index, path):
#如果目前path的长度和digits的长度相等,说明已经遍历完一趟,返回结果列表
if index == dlen:
result.append(path)
return
#遍历当前索引的数字对应的英文列表
for word in word_list[int(digits[index])]:
#路径加上当前字母
path = path + word
#递归下一个数字对应的英文列表
#print(path)
back_track(digits, index + 1, path)
#撤销当前字母
path = path[:-1]
#print(path)
back_track(digits, 0, "")
return result