给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。输入的数字范围为2-9,请你写出这个程序的代码
时间: 2023-03-13 22:07:00 浏览: 182
答:def get_combination(s):
res = []
mapping = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
}
def backtrack(comb, next_digits):
# if there is no more digits to check
if len(next_digits) == 0:
# the combination is done
res.append(comb)
# if there are still digits to check
else:
# iterate over all letters which map
# the next available digit
for letter in mapping[next_digits[0]]:
# append the current letter to the combination
# and proceed to the next digits
backtrack(comb + letter, next_digits[1:])
if s:
backtrack("", s)
return res
阅读全文