声明:
今天是中等题第10道题。给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。给出数字到字母的映射与电话按键相同。以下所有代码经过楼主验证都能在LeetCode上执行成功,代码也是借鉴别人的,在文末会附上参考的博客链接,如果侵犯了博主的相关权益,请联系我删除
(手动比心ღ( ´・ᴗ・` ))
正文
题目:给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:"23" 输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
解法1。调用了itertools中的product函数,先把digits中的数对应的字母读进来,然后求读进来的这不同组元素的product,代码如下。
执行用时: 40 ms, 在Letter Combinations of a Phone Number的Python3提交中击败了99.60% 的用户
class Solution:
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
import itertools
dic ={'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
alphas = [dic[d] for d in digits]
return [''.join(x) for x in itertools.product(*alphas)]
解法2。其实和解法1一样,只是把求product的过程具体化了,代码如下。
执行用时: 44 ms, 在Letter Combinations of a Phone Number的Python3提交中击败了89.48% 的用户
class Solution:
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
dic = {'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
alphas = [dic.get(d) for d in digits]
tmp = [[]]
# 下面这个for循环等同于解法1的itertools.product(*alphas)
for pool in alphas:
tmp = [x+[y] for x in tmp for y in alphas]
return [''.join(x) for x in tmp]
解法3。回溯
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if not digits:
return []
res = []
out = ''
dic = ['','','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']
self.helper(digits, dic, 0, out, res)
return res
def helper(self, digits, dic, level, out, res):
if level == len(digits):
res.append(out)
return
cur_str = dic[int(digits[level])]
for i in range(len(cur_str)):
self.helper(digits, dic, level+1, out+cur_str[i], res)
解法4。递归转为循环实现
class Solution:
def letterCombinations(self, digits):
if not digits:
return []
dic = {'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
res = [''] # 一定不能为空,因为这样在循环中会拿不到digits[0]对应的字符,''也算一个字符,只不过是空字符
for i in range(len(digits)):
t = []
strs = dic[digits[i]]
for j in range(len(strs)):
for str in res: # 相当于在前面level已成型的字符后加当前level的字符
t.append(str+strs[j])
res = t[:]
return res
结尾
解法1&解法2:https://blog.csdn.net/qq_17550379/article/details/82459849