[leetcode] 17. Letter Combinations of a Phone Number ,python實現【medium】

  1. Letter Combinations of a Phone Number

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

圖就不上了,意思是說,手機的9宮按鍵,2對應的是abc,3對應的def,這樣。要你給出所有的可能,這在數學上叫什麼乘機來着我忘了。。。
就是用遞歸或者dfs,比如給‘234’吧,先看2,那現在應該是[‘a’,’b’,’c’],
那再加上3呢,是不是在這個[‘a’,’b’,’c’]的基礎上,[‘a’,’b’,’c’]每一個的後面分別加上‘d’,’e’,’f’:也就是 [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”],
然後再加4的’g”h”i’,以此類推。

下面是python實現,就是爽,主要的遞歸函數就一行。不知道c++要多少行啊。。


class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        if digits == '':
            return []
        self.DigitDict=[' ','1', "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
        res = ['']
        for d in digits:
            res = self.letterCombBT(int(d),res)
        return res

    def letterCombBT(self, digit, oldStrList):
        return [dstr+i for i in self.DigitDict[digit] for dstr in oldStrList]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章