17. Letter Combinations of a Phone Number

Leetcode

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

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

Note: Although the above answer is in lexicographical order, your answer could be in any order you want.

手机按键上每个数字都对应了多个字母,如2对应了"abc",现给出一个数字串,要求把其中的每个数字都转化为对应的字母中的一个,列出所有的组合情况。

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

注意点:对结果的排列顺序没有要求

class Solution:
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        # 特殊情况,空字符串
        n = len(digits)
        if n == 0:
            return []

        self.dict = {"1":"", "2":"abc", "3":"def", "4":"ghi", "5":"jkl", "6":"mno", "7":"pqrs","8":"tuv","9":"wxyz","10":" "}

        result = [""]
        for digit in digits:
            lst = self.dict[digit]
            newresult = []
            for char in lst:
                for str in result:
                    newresult.append(str+char)
            result = newresult
        return result