思路 设置字母和数字映射字典,设置backtrack函数,参数index表示层数,用来遍历digits的(题目中给出数字字符串)
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
answers = []
answer = []
letter_map = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
}
def backtrack(digits, index):
if index == len(digits):
temp_str = ""
for temp in answer:
temp_str += temp
answers.append(temp_str)
return
letters = letter_map[digits[index]]
for letter in letters:
answer.append(letter)
backtrack(digits, index+1)
answer.pop()
if not digits: return []
backtrack(digits, 0)
return answers
|