LeetCode Letter Combinations of a Phone Number
来源:互联网 发布:通达信软件使用教程 编辑:程序博客网 时间:2024/05/22 03:37
LeetCode解题之Letter Combinations of a Phone Number
原题
手机按键上每个数字都对应了多个字母,如2对应了”abc”,现给出一个数字串,要求把其中的每个数字都转化为对应的字母中的一个,列出所有的组合情况。
注意点:
- 对结果的排列顺序没有要求
例子:
输入: digits=”23”
输出: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”]
解题思路
把每个数字对应的字母都当做树的节点,如下图,则所求结果就是从根节点到叶节点的所有的路径,采用深度优先遍历算法。
AC源码
class Solution(object): digit2letters = { '2': "abc", '3': "def", '4': "ghi", '5': "jkl", '6': "mno", '7': "pqrs", '8': "tuv", '9': "wxyz", } def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if not digits: return [] result = [] self.dfs(digits, "", result) return result def dfs(self, digits, current, result): if not digits: result.append(current) return for c in self.digit2letters[digits[0]]: self.dfs(digits[1:], current + c, result)if __name__ == "__main__": assert Solution().letterCombinations("23") == ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
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
- Visual Studio中丢失ArcGis Engine 控件的解决方法
- 《挑战程序设计竞赛》2.4.1 数据结构-优先队列 POJ2431 3253 3614 2010(3)
- cookie与session
- Unity中UGUI人物血条跟随的几种实现方式(二)
- Java:CoreJava篇:java.lang.String.getBytes()探索
- LeetCode Letter Combinations of a Phone Number
- iOS新版本特性(引导页)
- makefile中不推荐使用sinclude
- 学习vim有感
- 数据结构 — 堆排序
- 基于at91sam9x5ek嵌入式系统的内核和文件系统双备份实现
- 尾递归与Continuation
- 尾递归对时间与空间复杂度的影响(上)
- Lintcode - Naive Fibonacci