--

leetcode 017: Letter Combinations of a Phone Number



https://leetcode.com/problems/letter-combinations-of-a-phone-number/submissions/



problem:
Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.




Example:

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



start code (c++)
class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if len(digits) == 0:
            return []
        digit_to_abc = {
            '2':'abc',
            '3':'def',
            '4':'ghi',
            '5':'jkl',
            '6':'mno',
            '7':'pqrs',
            '8':'tuv',
            '9':'wxyz'
        }
        solutions = ['',]
        for i, d in enumerate(digits):
            newChars = digit_to_abc[d]
            solutions_temp = []
            for newChar in newChars:
                temp = [x + newChar for x in solutions]
                solutions_temp += temp
            solutions = solutions_temp
        return solutions        


solution:

我的思路:



class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if len(digits) == 0:
            return []
        digit_to_abc = {
            '2':'abc',
            '3':'def',
            '4':'ghi',
            '5':'jkl',
            '6':'mno',
            '7':'pqrs',
            '8':'tuv',
            '9':'wxyz'
        }
        solutions = ['',]
        for i, d in enumerate(digits):
            newChars = digit_to_abc[d]
            solutions_temp = []
            for newChar in newChars:
                temp = [x + newChar for x in solutions]
                solutions_temp += temp
            solutions = solutions_temp
        return solutions