zoukankan      html  css  js  c++  java
  • 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
            
  • 相关阅读:
    loadrunner 字符集与检查点的探讨
    oracle使用游标进行循环数据插入
    QTP之WinMenu对象的测试
    VBS数组深入浅出
    Loadrunner 如何访问数据库
    loadrunner字符串处理函数
    动态SQL现实一个表中求多列的和
    oracle中WMSYS.WM_CONCAT函数的版本差异
    强制卸载LINUX系统自带JDK
    loadrunner调用QTP脚本来实现性能测试(一次现场特殊需求的解决方案)
  • 原文地址:https://www.cnblogs.com/prmlab/p/7067616.html
Copyright © 2011-2022 走看看