1. 程式人生 > >leetcode 17. 電話號碼的字母組合 (python) 非遞迴

leetcode 17. 電話號碼的字母組合 (python) 非遞迴

給定一個僅包含數字 2-9 的字串,返回所有它能表示的字母組合。

給出數字到字母的對映如下(與電話按鍵相同)。注意 1 不對應任何字母。

示例:

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

說明:

本題用到字典,很簡單,很無腦,我寫了個非遞迴版的

class Solution:
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        shuju ={"2":"abc","3":"def","4":"ghi","5":"jkl","6":"mno","7":"pqrs","8":"tuv","9":"wxyz"}
        digits = list(digits)
        res =[]
        while digits:
            print(digits)
            print(res)
            a = digits.pop(0)
            if res == [] :#如果res沒有值直接加進去
                for i in shuju[a]:
                    res.append(i)
                    
            else :
                temp2 = []
                for i in shuju[a]:
                    temp = res
                    def fx(x):
                        return x+i
                    temp2 += list(map(fx,temp))
                res = temp2
        return res

提交後看到一個大神些的,相形見絀,思想和我一樣,程式碼如下(學習)

class Solution:
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        
        if not digits:
            return []
        
        digit2chars = {
            '2': 'abc',
            '3': 'def',
            '4': 'ghi',
            '5': 'jkl',
            '6': 'mno',
            '7': 'pqrs',
            '8': 'tuv',
            '9': 'wxyz'
        }
        
        res = [ i for i in digit2chars[digits[0]] ]
        
        for i in digits[1:]:
            res = [ m+n for m in res for n in digit2chars[i] ]
            print (res)
            
        return res