您的位置:首页 > 编程语言 > Python开发

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

2016-06-14 22:25 676 查看
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]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode python string