给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:“23”
输出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
解法1:暴力求解
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
# 创建字母对应的字符列表的字典
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'],
}
# 存储结果的数组
result = []
n = len(digits)
if n == 0:
return []
for s in dic[int(digits[n - 1])]:
result.append(s)
n -= 1
while n > 0:
temp = []
for i in dic[int(digits[n - 1])]:
for j in result:
temp.append(i + j)
result = temp
n -= 1
return result
解法2:递归
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
# 创建字母对应的字符列表的字典
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'],
}
# 存储结果的数组
result = []
if len(digits) == 0:
return []
# 递归出口 当递归到最后一个数的时候recur拿到结果进行for循环遍历
if len(digits) == 1:
return dic[int(digits)]
# 递归调用
recur = self.letterCombinations(digits[1:])
for r in recur:
for j in dic[int(digits[0])]:
result.append(j + r)
return result
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
# 创建字母对应的字符列表的字典
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'],
}
# 存储结果的数组
result = []
n = len(digits)
if n == 0:
return []
# 递归出口 当递归到最后一个数的时候recur拿到结果进行for循环遍历
if n == 1:
return dic[int(digits)]
# 递归调用
recur = self.letterCombinations(digits[:n-1])
for r in recur:
for j in dic[int(digits[n-1])]:
result.append(r + j)
return result