【LeetCode】17. Letter Combinations of a Phone Number 解题报告
2018-02-24 16:26
471 查看
【LeetCode】17. Letter Combinations of a Phone Number 解题报告
标签(空格分隔): LeetCode题目地址:https://leetcode.com/problems/generate-parentheses/description/
题目描述:
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.
解题方法
依然是回溯法。要求所有的可能的字符串的组合。有点类似784. Letter Case Permutation,不需要对index进行for循环,因为对index进行for循环产生的是所有可能的组合。而这两个题要求的组合的长度是固定的,每个位置都要有字母。
另外就是要判断一下
path != '',原因是当digits为”“的要求的结果是[],而不是[“”]。
class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ kvmaps = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'} res = [] self.dfs(digits, 0, res, '', kvmaps) return res def dfs(self, string, index, res, path, kvmaps): if index == len(string): if path != '': res.append(path) return for j in kvmaps[string[index]]: self.dfs(string, index + 1, res, path + j, kvmaps)
方法二:
使用python 自带的product笛卡尔乘积函数。
from itertools import product class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if not digits: return [] kvmaps = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'} answer = [] for each in product(*[kvmaps[key] for key in digits]): answer.append(''.join(each)) return answer
Date
2018 年 2 月 24 日相关文章推荐
- [leetcode] 17. Letter Combinations of a Phone Number 解题报告
- [Leetcode] 17. Letter Combinations of a Phone Number 解题报告
- [LeetCode] Letter Combinations of a Phone Number 解题报告
- [LeetCode] Letter Combinations of a Phone Number 解题报告
- leetcode解题之 17. Letter Combinations of a Phone Number java 版(键盘排列)
- leetCode 17.Letter Combinations of a Phone Number(电话数字对应的字母组合) 解题思路和方法
- LeetCode: Letter Combinations of a Phone Number 解题报告
- [LeetCode] Letter Combinations of a Phone Number 解题报告
- Letter Combinations of a Phone Number --leetcode解题报告
- [leetCode 解题报告]080. Letter Combinations of a Phone Number
- [leetcode]103. Binary Tree Zigzag Level Order Traversal@Java解题报告
- 【LeetCode】330.Patching Array(Hard)解题报告
- 【LeetCode】401. Binary Watch 解题报告
- [Leetcode] 3. Longest Substring without Repeating Characters 解题报告
- Leetcode 372. Super Pow 快速幂计算 解题报告
- [leetcode]110. Balanced Binary Tree@Java解题报告
- 【LeetCode】464.Can I Win(Medium)解题报告
- [leetcode] 121. Best Time to Buy and Sell Stock 解题报告
- leetcode解题报告(2):Remove Duplicates from Sorted ArrayII
- LeetCode: Next Permutation 解题报告