leetcode 17. Letter Combinations of a Phone Number

来源:互联网 发布:纽约大学录取条件 知乎 编辑:程序博客网 时间:2024/05/21 10:42

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

class Solution(object):    def output(self,digits,dep,cnt,ret,dictionary):        if len(digits)>=1:            if len(digits)==1:                for j in dictionary[digits[0]]:                    dep[cnt]=j                    ret.append(''.join(dep[:]))            else:                for j in dictionary[digits[0]]:                    dep[cnt]=j                    self.output(digits[1:],dep,cnt+1,ret,dictionary)        return ret    def letterCombinations(self, digit):        """        :type digits: str        :rtype: List[str]        """        dictionary={'2':['a','b','c'],                    '3':['d','e','f'],                    '4':['g','h','i'],                    '5':['j','k','l'],                    '6':['m','n','o'],                    '7':['p','q','r','s'],                    '8':['t','u','v'],                    '9':['w','x','y','z']}        num=len(digit)        dep=[0 for i in range(num)]        cnt=0        ret=[]        ans=self.output(digit,dep,cnt,ret,dictionary)        return ans
0 0
原创粉丝点击