This is actually a more efficient solution because I rather than completely rewriting over prev in the previous implementation, I pass in the updated seed (which is next), and return it in the end.
class Solution:
num_char = {'2': "abc", '3': "def", '4': "ghi",
'5': "jkl", '6': "mno", '7': "pqrs",
'8': "tuv", '9': "wxyz"}
def __letter_combinations(self, digits, index, seed):
"""
:type digits: str
:type iter int
:type seed List[str]
:rtype: void
"""
if index < len(digits):
target = self.num_char[digits[index]]
next = [prev + char for prev in seed for char in target]
return self.__letter_combinations(digits, index + 1, next)
else:
return seed
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
digits = ''.join(digit for digit in digits if int(digit) > 1)
if not digits:
return []
seed = [char for char in self.num_char[digits[0]]]
return self.__letter_combinations(digits, 1, seed)
#testing
obj = Solution()
result = obj.letterCombinations("239")
print(result)
Python Solution 2
Incrementally build off the base case, and just keep adding to it.
num_char = {'2': "abc", '3': "def", '4': "ghi",
'5': "jkl", '6': "mno", '7': "pqrs",
'8': "tuv", '9': "wxyz"}
class Solution:
def _letterCombinations(self, current, digit):
new_current = []
for comb in current:
for char in num_char[digit]:
new_current.append(comb+char)
return new_current
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if not digits: return []
current = [char for char in num_char[digits[0]]]
if len(digits) == 1: return current
for digit in digits[1:]:
current = self._letterCombinations(current, digit)
return current