电话号码的字母组合

题目:给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。输入:"23"输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

来源:

法一:自己的代码

思路:无脑暴力循环,毫无技术含量

class Solution:
    def letterCombinations(self, digits: str):
        l = len(digits)
        dict = { 2:'abc', 3:'def', 4:'ghi', 5:'jkl',
                 6:'mno', 7:'pqrs',8:'tuv', 9:'wxyz'}
        # 对字典中的字符串进行分割
        def fenge(x):
            x_list = []
            for i in range(len(x)):
                x_list.append(x[i])
            return x_list
        # 对两个list进行笛卡尔积合并
        def hebin(x,result):
            if len(result) == 0:
                return x
            else:
                result_ = []
                for i in x:
                    for j in result:
                        result_.append(j+i)
            return result_
        # 如果l为空,直接返回[]
        if l == 0:
            return []
        result = []
        # for循环实现list的合并
        for i in range(l):
            a = digits[i]
            dic_val = dict[int(a)]
            dic_val = fenge(dic_val)
            result = hebin(dic_val, result)
        return result
if __name__ == "__main__":
    duixiang = Solution()
    a = duixiang.letterCombinations('3')
    print(a)
View Code

法二:官网的代码

思路:利用回朔算法,回朔的终止条件是从digits中都取了一个字符了,否则继续,回朔函数每次都合并一个字母,这个算法耗时最短,超过百分之99的用户.

class Solution:
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        phone = {'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']}

        def backtrack(combination, next_digits):
            if len(next_digits) == 0:
                # 如果next_digits长度为0,则说明从digits中的每个数中都取了一个字母了.
                # 则将得到的字符串放入output中
                output.append(combination)
            # 否则继续取字符
            else:
                # 由于每个数字对应多个字母,故用for循环
                for letter in phone[next_digits[0]]:
                    # 每次回朔的时候都把for循环中的数字去掉,并且把letter合并如combination中
                    backtrack(combination + letter, next_digits[1:])
        output = []
        if digits:
            backtrack("", digits)
        return output

if __name__ == "__main__":
    duixiang = Solution()
    a = duixiang.letterCombinations('23')
    print(a)
View Code

 

 

posted on 2019-11-24 17:44  吃我一枪  阅读(235)  评论(0编辑  收藏  举报

导航