Easy Python version with recursion

  • 0
    class Solution:
        # @return a list of strings, [s1, s2]
        def __init__(self):
            self.map = [None, None, 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
            self.output = []
        def letterCombinations(self, digits, pos = 0, string = None):
            if string is None:
                string = []
            if pos == 0:
                digits = filter(lambda x: x not in '01', digits)
            if len(string) == len(digits):
                return self.output
            for c in self.map[int(digits[pos])]:
                self.letterCombinations(digits, pos + 1, string)
            return self.output

  • 0

    Also python version recursion:

    class Solution:
        # @param {string} digits
        # @return {string[]}
        def __init__(self):
            self.m = {'2':'abc', '3':'def', '4':'ghi', '5':'jkl', '6':'mno', '7':'pqrs', '8':'tuv', '9':'wxyz'}
        def letterCombinations(self, digits):
            return [] if not digits else self.aux(digits, 0)
        def aux(self, digits, i):
            return [''] if i == len(digits) else [s + t for t in self.aux(digits, i+1) for s in self.m[digits[i]]]

Log in to reply

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