首页 > 其他 > 详细

电话号码的字母组合

时间:2019-04-05 16:13:05      阅读:121      评论:0      收藏:0      [点我收藏+]

题目描述:

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例:

输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

技术分享图片

class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        if len(digits) == 0:
            return []
            
        d = {1: "", 2: "abc", 3: "def", 4: "ghi", 5: "jkl", 6: "mno", 7: "pqrs", 8: "tuv", 9: "wxyz"}
        
        def dfs(digits, index, path, res, d):
            if index == len(digits):
                res.append("".join(path))
                return 
        
            digit = int(digits[index])
            for c in d.get(digit, []):
                path.append(c)
                dfs(digits, index + 1, path, res, d)
                path.pop()
        
        res = []
        dfs(digits, 0, [], res, d)
        return res
                
class Solution:
    def letterCombinations(self, digits: str):
        keys = {2:abc,3:def,4:ghi,5:jkl,6:mno,7:pqrs,8:tuv,9:wxyz}
        words= [keys[_] for _ in digits if _ in keys]
        if len(words) == 0:
            return []
        else:
            ans = [_ for _ in words[0]]
        for i in range(1,len(words)):
            temp = ans
            for j in range(len(words[i])):
                a = [(_ + words[i][j]) for _ in temp]
                if j == 0:
                    ans = a
                else:
                    ans += a

        return ans

 

 

 

电话号码的字母组合

原文:https://www.cnblogs.com/Estate-47/p/10658866.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!