LintCode 电话号码的字母组合

来源:互联网 发布:电脑专业录音软件 编辑:程序博客网 时间:2024/04/30 15:56

Given a digit string excluded 01, 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.

样例
给定 “23”
返回 [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”]

题意解释:给定一个数字字符串,不包括数字0和1。每个数字可以代表的字母就是手机输入法9键输入的那个对应关系。求得所有可能代表的字母组合。

第一反应就是循环输出就好了。。但是给定字符串长度不确定,不知道循环多少次,那么这就交给程序自行去判断吧,就用递归。
代码:

class Solution:    """    @param: digits: A digital string    @return: all posible letter combinations    """    def letterCombinations(self, digits):        # write your code here        table = [" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]        if len(digits)==0:            return []        tempresult="" #临时存每一个可能的字母字符串        result=[]   #所有结果        self.recursion(table,0,digits,tempresult,result)        return result    def recursion(self,table,count,digits,tempresult,result):    #count是记录处理到第几个数字了    if len(digits)==len(tempresult):            result.append(tempresult)            return         for c in table[int(digits[count])]:            tempresult+=c            self.recursion(table,count+1,digits,tempresult,result)            tempresult=tempresult[:-1]#一次循环结束时,要把最后添加的字母去掉