easy to understand python solution


  • 0
    Z
    class Solution(object):
        dic = {'2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'],
               '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z']}
    
        def letterCombinations(self, digits):
            """
            :type digits: str
            :rtype: List[str]
            """
            # for i in digits:
            #     if i not in self.dic:
            #         return []
            if digits == '':
                return []
            res = []
            ans = self.divide(digits)
            for index in self.get_index(ans):
                temp = ''
                for i in range(len(index)):
                    temp += ans[i][index[i]]
                res.append(temp)
    
            return res
    
        def divide(self, digits):
            res = []
            for i in range(len(digits)):
                res.append(self.dic[digits[i]])
            return res
    
        def get_index(self, ans):
            res = []
            leng = len(ans)
            for i in range(leng):
                res.append(0)
            mult = 1
            for i in ans:
                mult *= len(i)
            for i in range(mult):
                for j in range(leng):
                    if res[leng - 1 - j] == len(ans[leng - 1 - j]):
                        res[leng - 1 - j] = 0
                        res[leng - 2 - j] += 1
                yield res
                res[-1] += 1
    

Log in to reply
 

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