[Leetcode]Letter Combinations of a Phone Number
来源:互联网 发布:消防海湾主机编程实例 编辑:程序博客网 时间:2024/04/29 16:35
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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
给定一串数字,求出在电话按键中可能得到的字母组合~可以用DFS来做,维护一个数组digitToLetters,表示每个数字对应代表的字母~
class Solution: # @return a list of strings, [s1, s2] def letterCombinations(self, digits): if digits is None or len(digits) == 0: return [""] self.res = [] self.digitToLetters = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] self.helper(digits, 0, []) return self.res def helper(self, digits, index, item): if len(digits) == index: self.res.append(''.join(item)) return for c in self.digitToLetters[int(digits[index])]: item.append(c) self.helper(digits, index + 1, item) item.pop()还有非递归解法,依次读取数字,然后把数字可以代表的字符依次加到当前的所有结果中,然后进入下一次迭代,代码如下~
class Solution: # @return a list of strings, [s1, s2] def letterCombinations(self, digits): if digits is None or len(digits) == 0: return [""] res = [""] digitToLetters = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] for i in xrange(len(digits)): newRes = [] for c in digitToLetters[int(digits[i])]: for j in xrange(len(res)): newRes.append(res[j] + c) res = newRes return res
0 0
- LeetCode: Letter Combinations of a Phone Number
- LeetCode Letter Combinations of a Phone Number
- LeetCode: Letter Combinations of a Phone Number
- [Leetcode] Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- 【leetcode】Letter Combinations of a Phone Number
- LeetCode: Letter Combinations of a Phone Number
- [LeetCode]Letter Combinations of a Phone Number
- LeetCode-Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- LeetCode - Letter Combinations of a Phone Number
- LeetCode:Letter Combinations of a Phone Number
- LeetCode | Letter Combinations of a Phone Number
- leetcode Letter Combinations of a Phone Number
- Leetcode: Letter Combinations of a Phone Number
- 【leetcode】Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- leetcode: Letter Combinations of a Phone Number
- 结合Android学设计模式--工厂方法(FactoryMethod)
- 代码手写UI,xib和StoryBoard间的博弈,以及Interface Builder的一些小技巧
- 辗转相除法---切蛋糕
- Android学习笔记 - TabHost 和 Menu(一)
- 为何使用动态代理
- [Leetcode]Letter Combinations of a Phone Number
- su & sudo
- Caffe 深度学习框架上手教程
- Linux flash 文件系统剖析
- ym——Android仿网易新闻导航栏PagerSlidingTabStrip源码分析
- C字符串输入输出
- 绘制SVG内容到Canvas的HTML5应用
- urllib2模块之异常处理
- [BestCoder] Round #4