1. 程式人生 > >演算法35--Letter Combinations of a Phone Number

演算法35--Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

Example:

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

給定一組陣列,利用九鍵拼音輸入法將其轉化為可能的字母組合。

首先定義數字與字元的對應關係:

dict={'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}

給定數字234  首先考慮第一位2,其對應abc有三種取值情況,此時若已知23的所有組合,則將abc依次與23返回的所有字元一一結合,依次類推,可以遞歸向下,直至最後只有一個數字,可以直接返回即可。邊界條件要考慮輸入為空以及輸入中有數字1的情況。

class Solution:
    def letterCombinations(self, digits='23'):
        """
        :type digits: str
        :rtype: List[str]
        """
        dict={'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
        return help(digits, dict)
 
def help(s, dict):
    if s=='':
        return []
    if len(s)==1:
        if s=='1':
            return []
        else:
           r=[]
           ss = dict[s]
           for v in ss:
               r.append(v)
           return r
    else:
        tt=[]
        rr = help(s[1:], dict)
        for v in dict[s[0]]:
            for vv in rr:
                tt.append(v+vv)
        return tt

參考一下大神的程式碼,充分利用python的列表推導式如下:

class Solution:
    def letterCombinations(self, digits='23'):
        """
        :type digits: str
        :rtype: List[str]
        """
        dict={'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
        return help(digits, dict)
 
def help(s, dict):
    if s=='' or (len(s)==1 and s=='1'):
        return []
    if len(s)==1 and s!='1':
        return [v for v in dict[s]]      
    else:
        return [v+vv for v in dict[s[0]] for vv in help(s[1:], dict)]