LeetCode[Backtracking]: Letter Combinations of a Phone Number
来源:互联网 发布:php开发环境搭建教程 编辑:程序博客网 时间:2024/06/06 17:23
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”].
思路:这个题目有个特点就是每一个结果的长度都等于输入的digits的长度,每继续按一个键都是前面所有的结果与当前这个键对应的所有字母的组合。比方说一开始按了”2”,对应的结果是[“a”,”b”,”c”],再按一个”3”,就是前面的产生的”a”与”d”、”e”、”f”的组合[“ad”,”ae”,”af”],前面的产生的”b”与”d”、”e”、”f”的组合[“bd”,”be”,”bf”],前面的产生的”c”与”d”、”e”、”f”的组合[“cd”,”ce”,”cf”]。
代码如下:
class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if len(digits) == 0: return [] mapping = ('0', '1', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz') result = ['', ] for digit in digits: temp, result = result, [] for item in temp: for letter in mapping[int(digit)]: result.append(item + letter) return result
时间性能如下图所示:
阅读全文
0 0
- LeetCode[Backtracking]: Letter Combinations of a Phone Number
- Backtracking: 17. Letter Combinations of a Phone Number
- (M)Backtracking:17. 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
- 过去·现在·将来
- HDU 1811 Rank of Tetris 并查集+拓扑排序
- 理解 Javascript 中变量的作用域
- JVM 垃圾回收器工作原理及使用实例介绍
- css 字体颜色渐变
- LeetCode[Backtracking]: Letter Combinations of a Phone Number
- 迪士尼乐园全套源码分享带急速赛车,后台带AB盘完美无错
- mysql导出数据
- jquery表单选择器input、:text、:password、:radio、:checkbox、:submit、:reset、:image、:button、:file、:hidden
- jstl标签格式化字符串日期
- win7C++程序移植到Linux出现的问题
- iOS项目基础框架
- Thinkphp基础入门(适合php新手)
- 用于AngularJS的UI路由器