Leetcode -17. Letter Combinations of a Phone Number

这个问题我最开始的想的是使用树的结构去做,之后用python实现的时候是使用了几个for循环:

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'}
        ans = []
        i = 0
        """
        读取输入的数字,如果试一次输入,直接将第一个数字对应的字母分别添加进入ans
        """
        for s in digits:    
            if ans == []:
                for st in dic[s]:
                    ans.append(st)
                i += 1
            """
            读取已存在的letter combinations
            """
            else:       
                l = len(ans)
                """
                对letter combinations分别添加新的letter 并 生成新的 letter combinations
                """
                for j in range(l):
                    for st1 in dic[s]:  
                        ans.append(ans[j]+st1)    
                """
                因为是直接将新的letter combinations添加进入ans,所以需要删除旧的letter combinations
                """
                ans = ans[j+1:] 
                i += 1
        return ans

在discuss区中,排名第一的算法(one line python):

class Solution:
    # @return a list of strings, [s1, s2]
    def letterCombinations(self, digits):
        if '' == digits: return []
        kvmaps = {
            '2': 'abc',
            '3': 'def',
            '4': 'ghi',
            '5': 'jkl',
            '6': 'mno',
            '7': 'pqrs',
            '8': 'tuv',
            '9': 'wxyz'
        }
        return reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, [''])
        # ['']为初始参数,即acc, digits为可循环参数:x = [], digit = _ for _ in digits

语法

reduce() 函数语法:

reduce(function, iterable[, initializer])

参数

  • function -- 函数,有两个参数
  • iterable -- 可迭代对象
  • initializer -- 可选,初始参数

猜你喜欢

转载自blog.csdn.net/yinzhuochao/article/details/83584223
今日推荐