17. Letter Combinations of a Phone Number

https://leetcode.com/problems/letter-combinations-of-a-phone-number/#/description

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

Sol 1:

Recursion.

The base case is when the only one digit of the input digits left. Then we output the letters that the number represents.

We will call the method recursively on the input number but the last digit. Then set an additional variable that stores the hash value, i.e. the letters of the last input digit. Finally, we return the combination of recursive values and the additional value. 

Time O(3^n), space O(n)

class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        
        hash = {'2' : 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
        if len(digits) == 0:
            return []
        
        # base case
        if len(digits) == 1:
            return list(hash[digits[0]])
        
        #recursion
        prev = self.letterCombinations(digits[:-1])
        additional = hash[digits[-1]]
        return [s + c for s in prev for c in additional] 

Note:

1 list() turns sequances into lists mandatorily.  

2 Quite pythonic to write return like that.  

Sol 2:

Iteration. 

Append two parts to the finial ouput. 1) Previous result. 2) Current hash value. Do that using for loop. 

Time O(3^n), space O(n) 

class Solution(object):
    def letterCombinations(self, digits):
        
        if len(digits) == 0:
            return []
        
        
        _hash = {"1": "", "2" : "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"}
        
        
        results = []
        results.append("")
        
        if not digits.isdigit():
            return results
            
        for digit in digits:
            if digit == '1':
               continue
            word = _hash[digit]
            tmp = []
            for let in word:
                for res in results:
                    tmp.append(res + let)
            results = tmp
            
        return results
        
原文地址:https://www.cnblogs.com/prmlab/p/7067616.html