Recursive solution in Python


  • 0
    H
    class Solution(object):
        def letterCombinations(self, digits):
            """
            :type digits: str
            :rtype: List[str]
            """
            def combine_letter(D, digits, letters):
                if len(digits) == 0:
                    return letters
                chars = D[digits[0]]
                m = len(chars)
                letters_list = [[x for x in letters] for i in range(m)]
                for i in range(m):
                    if len(letters_list[i]) == 0:
                        letters_list[i] = chars[i]
                    else:
                        for j in range(len(letters_list[i])):
                            letters_list[i][j] = letters_list[i][j] + chars[i]  # do not use append here
    
                letters = [letters_list[i][j] for i in range(m) for j in range(len(letters_list[i]))]
                return combine_letter(D, digits[1:], letters)
    
            
            n = len(digits)
            res = []
            if n == 0:
                return []
            D = {'2':'abc', '3':'def', '4':'ghi', '5':'jkl', '6':'mno', '7':'pqrs', '8':'tuv', '9':'wxyz'}
            res = combine_letter(D, digits, [])
            return res
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.