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.
classSolution: 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 seeddefletterCombinations(self,digits):""" :type digits: str :rtype: List[str] """ digits =''.join(digit for digit in digits ifint(digit) >1)ifnot digits:return [] seed = [char for char in self.num_char[digits[0]]]return self.__letter_combinations(digits, 1, seed)#testingobj =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"}classSolution:def_letterCombinations(self,current,digit): new_current = []for comb in current:for char in num_char[digit]: new_current.append(comb+char)return new_currentdefletterCombinations(self,digits):""" :type digits: str :rtype: List[str] """ifnot digits:return [] current = [char for char in num_char[digits[0]]]iflen(digits)==1:return currentfor digit in digits[1:]: current = self._letterCombinations(current, digit)return current