LeetCode-Python-17. 电话号码的字母组合

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

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

示例:

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

说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。

 

思路:

先建好数字和字母的mapping字典,然后类似于LeetCode-Python-78. 子集的第二种思路

第二种思路:

线性扫描,读取k+1个数时,把前k个数的所有子集都新加入一个k+1,形成含有这个k+1的所有子集,再把它们放入result。

对于每个数字的每个字符来说,把它加到目前已有的每个解里去, 暴力解就行……

class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        mapping = {2:"abc", 3:"def", 4:"ghi", 5:"jkl", 6:"mno", 7:"pqrs", 8:"tuv", 9:"wxyz"}
        
        res = []
        for digit in digits:
            temp = []
            n = int(digit)
            for char in mapping[n]:
                # print char
                if not res:
                    temp.append(char)
                else:
                    for item in res:
                        temp.append(item + char)
            res = temp
            # print res
        
        return res

 


版权声明:本文为qq_32424059原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。