17.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.

avatar

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.

class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        if len(digits)==0:
            return []
        dict = {2:"abc",3:"def",4:"ghi",5:"jkl",6:"mno",7:"pqrs",8:"tuv",9:"wxyz"}
        res = []
        def generate(a,index):
            if len(a)==len(digits): #递归出口
                res.append(a)
                return
            curnum = int(digits[index]) #当前数字
            for i in dict[curnum]: #把当前数字的字母逐个加入到a中,
                temp = a #保存加入之前的字符串,以便恢复
                a += i
                generate(a,index+1) #递归到下一个位置
                a = temp
        generate('',0)
        return res
posted @ 2018-11-30 15:15  bernieloveslife  阅读(156)  评论(0编辑  收藏  举报