3 回答
TA贡献1864条经验 获得超6个赞
我不明白你为什么要这样做for n in digits:,每次回溯时,你应该只关注当前数字 ( digits[0]),遍历该数字的所有可能值,然后将其余工作传递给下一个递归称呼。删除该行并更改n以digits[0]解决您的问题:
def letterCombinations(digits):
"""
:type digits: str
:rtype: List[str]
"""
letters = {'2':'abc', '3':'def','4':'ghi', '5':'jkl', '6':'mno', '7':'pqrs','8':'tuv', '9':'wxyz'}
def backtrack(digits, path, res):
if digits == '':
res.append(path)
return
for letter in letters[digits[0]]:
# note that you can replace this section with
# backtrack(digits[1:], path + letter, res)
path += letter
backtrack(digits[1:], path, res)
path = path[:-1]
res = []
backtrack(digits, '', res)
return res
letterCombinations('23')
输出:
['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']
此外,您应该考虑@DYZ 的超级简洁和令人敬畏的解决方案,它使用itertools:
import itertools
letters = {'2':'abc', '3':'def','4':'ghi', '5':'jkl', '6':'mno', '7':'pqrs','8':'tuv', '9':'wxyz'}
def letterCombinations(digits):
return ["".join(combo) for combo in itertools.product(*[letters[d] for d in digits])]
print(letterCombinations('23'))
输出:
['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']
TA贡献1712条经验 获得超3个赞
让我们从伪代码中看一下:
if digits is empty
path is a solution
else
for each letter in current digit
stick the letter on the front of
the letter combos for the rest of the input
这给了我们更短的编程:
def backtrack(digits, path, res):
if len(digits) == 0:
res.append(path)
else:
for letter in letters[digits[0]]:
backtrack(digits[1:], letter + path, res)
TA贡献1796条经验 获得超7个赞
In [34]: def get_prod(number_list):
...: let_list = [nums[i] for i in number_list]
...: r = [[]]
...: for p in let_list:
...: r = [x + [y] for x in r for y in p]
...: return [''.join(i) for i in r]
...:
...:
In [35]: get_prod(['2', '3', '4'])
Out[35]:
['adg',
'adh',
'adi',
'aeg', ...
添加回答
举报