LeetCode演算法題python解法:17. Letter Combinations of a Phone Number

來源:互聯網
上載者:User

標籤:ber   like   個數   自動   def   map   ike   ica   else   

題目:

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"].

Note:

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

這道題翻譯成中文其實比較簡單,就是給你數字,讓你輸出數字映射的字母所有可能出現的組合情況。同一個數字映射的字母不會組合到一起,不區分字母順序,每個字母組合必須包含所有數字映射的一個字母。

這裡利用遞迴可以輕鬆解決,剛好最近看了一些產生器相關的資料,索性利用遞迴產生器,更加簡潔方便一些。

代碼如下:

 1 class Solution: 2     def letterCombinations(self, digits): 3         return list(self.recur(digits))     
4 def recur(self, x): #由於LeetCode驗證代碼時不會自動將產生器轉化為列表,所以只能產生器寫在外面,主函數只列印答案 5 dic = {‘2‘: ‘abc‘, ‘3‘: ‘def‘, ‘4‘: ‘ghi‘, ‘5‘: ‘jkl‘, ‘6‘: ‘mno‘, ‘7‘: ‘pqrs‘, ‘8‘: ‘tuv‘, ‘9‘: ‘wxyz‘} 6 if len(x) == 0: #將digits為空白值拿出來特別處理 7 return [] 8 for i in dic[x[0]]: 9 if len(x) == 1: #遞迴到digits只剩最後一個值挨個產生該值的映射 10 yield i11 else:12 for j in self.letterCombinations(x[1:]): #這裡返回的產生器,可以用來迭代13 yield i + j #拼接字串,一層一層向上返還

 

LeetCode演算法題python解法:17. Letter Combinations of a Phone Number

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.