给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2:
输入:digits = ""
输出:[]
示例 3:
输入:digits = "2"
输出:["a","b","c"]
关于映射,这里本人用的是asll转换并且条件判断,官方给的是直接存储值…
class Solution:
def numberToLetters(self,n,r=3,c=0):# 数字转换,n为数字,r为数量,c为偏移量
target = ord(n)
res = []
for i in range(r):
res.append(chr(target + 47 + i + (int(n)-2)*2+c))
return res
def mapManage(self,n): # 数字映射
if(int(n)<=6):
return self.numberToLetters(n)
elif(n == '7'):
return self.numberToLetters('7',4,0)
elif(n == '8'):
return self.numberToLetters('8',3,1)
else:
return self.numberToLetters('9',4,1)
def multiply(self,a,b):# 进行相乘
res = []
for m in a:
for n in b:
res.append(m+n)
return res
def letterCombinations(self, digits: str) -> List[str]:
if(digits == ""):return []
if(len(digits) == 1):return self.mapManage(digits)
res = []
target = []
for i in digits:
target.append(self.mapManage(i))
res = target[0]
for i in range(1,len(target)):
res = self.multiply(res,target[i])
return res
官方:
回溯
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits:
return list()
phoneMap = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz",
}
def backtrack(index: int):
if index == len(digits):
combinations.append("".join(combination))
else:
digit = digits[index]
for letter in phoneMap[digit]:
combination.append(letter)
backtrack(index + 1)
combination.pop()
combination = list()
combinations = list()
backtrack(0)
return combinations