LeetCode-17. Letter Combinations of a Phone Number(电话号码的字母组合)

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

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

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

Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

 方法一:遍历

首先要意识到,在用遍历的方法进行组合时,要借助字典把我们要用到的键—值对一一列出。比如这样:

 d = {"2":"abc","3":"def","4":"ghi","5":"jkl","6":"mno","7":"pqrs","8":"tuv","9":"wxyz"}

假设现在给的数是"234",用res来存储结果,那么这个过程如下: 

res = []                                                                                                                                                                                            res = ['a', 'b', 'c'],
res = ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']
res = ['adg', 'adh', 'adi', 'aeg', 'aeh', 'aei', 'afg', 'afh', 'afi', 'bdg', 'bdh', 'bdi', 'beg', 'beh', 'bei', 'bfg', 'bfh', 'bfi', 'cdg', 'cdh', 'cdi', 'ceg', 'ceh', 'cei', 'cfg', 'cfh', 'cfi']

#Python
class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        d = {"2":"abc","3":"def","4":"ghi","5":"jkl","6":"mno","7":"pqrs","8":"tuv","9":"wxyz"}
        if len(digits) == 0:    
            return []
        elif len(digits) == 1:    #只有一个数字的情况
            return list(d[digits])
        
        l_dig = len(digits)
        res = [""]
        for i in range(l_dig):    
            strs = d[digits[i]]    #取i+1序号下数字所代表的字符串
            temp = []
            for j in range(len(res)):    #取现有结果中第j+1个字符组合
                for k in range(len(strs)):    #现有结果的第j+1个组合都要依次加上当前处理字符串的每个字符
                    temp.append(res[j] + strs[k])
            res = temp    #更新结果
        return res

 

你可能感兴趣的:(算法)