Skip to content

Latest commit

 

History

History
35 lines (26 loc) · 827 Bytes

17.md

File metadata and controls

35 lines (26 loc) · 827 Bytes

Letter Combinations of a Phone Number

Description

link


Solution

使用迭代的方法,每次只处理最后一个自负,将他们全排列即可


Code

O(3^n)

class Solution:
    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'}
        if len(digits) == 0:
            return []
        if len(digits) == 1:
            return list(mapping[digits[0]])
        prev = self.letterCombinations(digits[:-1])
        additional = mapping[digits[-1]]
        return [s + c for s in prev for c in additional]