[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++要多少行啊。。
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]
相关文章推荐
- Android之获取手机上的图片和视频缩略图thumbnails
- android string.xml文件中的整型和string型代替
- Android java 与 javascript互访(相互调用)的方法例子
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- android上改变listView的选中颜色
- String.intern