【LeetCode】17. Letter Combinations of a Phone Number 电话号码的字母组合
- 作者: 负雪明烛
- id: fuxuemingzhu
- 个人博客:http://fuxuemingzhu.cn/
- 个人公众号:负雪明烛
- 本文关键词:电话号码, 字母组合,回溯法,题解,leetcode, 力扣,Python, C++, Java
题目地址:https://leetcode.com/problems/generate-parentheses/description/
题目描述
Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.
Example:
Input: "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 为""
的要求的结果是 []
,而不是 [""]
。
Python代码如下:
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)
如果不新增函数,而是直接使用题目给出的函数,也可以很快写出代码。唯一要注意的是,当题目输入为""
的时候,要返回{},那么for循环就没法遍历,所以我给他添加成了{""}
,这样循环就能进行了。
class Solution {
public:
vector<string> letterCombinations(string digits) {
if (digits.size() == 0) return {};
vector<string> res;
for (char d : board[digits[0]]) {
auto next = letterCombinations(digits.substr(1));
if (next.size() == 0)
next.push_back("");
for (string n : next) {
res.push_back(d + n);
}
}
return res;
}
private:
unordered_map<char, string> board = {{'2', "abc"}, {'3', "def"}, {'4', "ghi"}, {'5', "jkl"}, {'6', "mno"}, {'7', "pqrs"}, {'8', "tuv"}, {'9', "wxyz"}};
};
内置函数
使用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
循环
使用循环也能轻松把这个题目给搞定。使用结果数组res表示遍历到当前的位置已有的结果,那么再遍历下一个位置的时候,把这个位置能形成的所有结果和原来的进行两两组合。
python代码如下:
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if digits == "": return []
d = {'2' : "abc", '3' : "def", '4' : "ghi", '5' : "jkl", '6' : "mno", '7' : "pqrs", '8' : "tuv", '9' : "wxyz"}
res = ['']
for e in digits:
res = [w + c for c in d[e] for w in res]
return res
日期
2018 年 2 月 24 日
2018 年 12 月 21 日 —— 一周就要过去了
2019 年 1 月 8 日 —— 别熬夜,我都开始有黑眼圈了。。
【LeetCode】17. Letter Combinations of a Phone Number 电话号码的字母组合的更多相关文章
- [LeetCode] 17. Letter Combinations of a Phone Number 电话号码的字母组合
Given a string containing digits from 2-9inclusive, return all possible letter combinations that the ...
- [LeetCode]17. Letter Combinations of a Phone Number电话号码的字母组合
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that th ...
- Leetcode 17. Letter Combinations of a Phone Number(水)
17. Letter Combinations of a Phone Number Medium Given a string containing digits from 2-9 inclusive ...
- [LintCode] Letter Combinations of a Phone Number 电话号码的字母组合
Given a digit string, return all possible letter combinations that the number could represent. A map ...
- [leetcode 17]Letter Combinations of a Phone Number
1 题目: Given a digit string, return all possible letter combinations that the number could represent. ...
- Java [leetcode 17]Letter Combinations of a Phone Number
题目描述: Given a digit string, return all possible letter combinations that the number could represent. ...
- Leetcode 17.——Letter Combinations of a Phone Number
Given a digit string, return all possible letter combinations that the number could represent. A map ...
- [leetcode]17. Letter Combinations of a Phone Number手机键盘的字母组合
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that th ...
- [LeetCode] 17. Letter Combinations of a Phone Number ☆☆
Given a digit string, return all possible letter combinations that the number could represent. A map ...
随机推荐
- char和varchar2
1.CHAR的长度是固定的,而VARCHAR2的长度是可以变化的. 比如,存储字符串"abc",对于CHAR (10),表示你存储的字符将占10个字节(包括7个空字符) 而同样的V ...
- Linux-设置终端界面的字体颜色和自定义常用快捷功能
.bashrc是一个隐藏的文件,要打开并修改该文件需要: (0)命令:cd ~ (1)命令:ls -a 找到文件 .bashrc: (2) 命令 vim ~/.bashrc 进入到文件: (3) 直接 ...
- 分布式服务治理框架Dubbo的前世今生及应用实战
Dubbo的出现背景 Dubbo从开源到现在,已经出现了接近10年时间,在国内各大企业被广泛应用. 它到底有什么魔力值得大家去追捧呢?本篇文章给大家做一个详细的说明. 大规模服务化对于服务治理的要求 ...
- How To Call An Ambulance
How to Talk to the Emergency Dispatcher [minutesmatter.upmc稻糠亩] How To Call An Ambulance [askambulan ...
- pymongdb入门
Pymongo入门 安装 pip install pymongo 连接 实际就是实例化一个客户端对象,然后客户端对象中指定一个库作为库对象,库对象中的集合对象就是之后常用来执行操作的对象 1 ''' ...
- django数据库增删改查
django中数据库基本操作: 1.同步数据库 python manage.py makemigrations #生成migrations python manage.py migrate #应用mi ...
- 生产环境高可用centos7 安装配置RocketMQ-双主双从-同步双写(2m-2s-sync)
添加hosts信息[四台机器] vim /etc/hosts 192.168.119.130 rocketmq-nameserver1 192.168.119.130 rocketmq-master1 ...
- css通配样式初始化(多款,供君自选)
腾讯官网 body,ol,ul,h1,h2,h3,h4,h5,h6,p,th,td,dl,dd,form,fieldset,legend,input,textarea,select{margin:0; ...
- 乱序拼图验证的识别并还原-puzzle-captcha
一.前言 乱序拼图验证是一种较少见的验证码防御,市面上更多的是拖动滑块,被完美攻克的有不少,都在行为轨迹上下足了功夫,本文不讨论轨迹模拟范畴,就只针对拼图还原进行研究. 找一个市面比较普及的顶像乱序拼 ...
- keil 生成 bin 文件 gd32为例
fromelf --bin --output .\update\GD32F4xZ.bin .\Output\GD32450Z_EVAL.axf代表使用的keil内的工具代表输出公式,..表示: 输出 ...