没看答案。
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
res = []
track = []
k = len(digits)
choice = []
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']
}
if not digits:
return []
# 所有选择都加到数组choice中
for num in digits:
choice += dic[int(num)]
def backtrack(track, start, pos):
'''
track:路径数组
start: 循环的起始位置
pos:digits中的第pos个数字,它决定了循环结束end的位置
'''
if len(track) == k:
res.append(''.join(track))
return
end = start+len(dic[int(digits[pos])])
for cho in range(start, end):
track.append(choice[cho])
# 因为数字对应的数组长度有3或4,所以start位置需要分情况计算
# start和end的计算都是剪枝操作
if choice[cho] in dic[7] or choice[cho] in dic[9]:
start = cho + 4 - (cho-start) % 4
else:
start = cho + 3 - (cho-start) % 3
pos += 1
backtrack(track, start, pos)
pos -= 1
track.pop()
backtrack(track, 0, 0)
return res