【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 ...
随机推荐
- zabbix-磁盘状态脚本
#/bin/sh Device=$1 DISK=$2 case $DISK in tps) iostat -dmt 1 2|grep "\b$Device\b"|tail -1|a ...
- EXCEL-表格安全性:加密给与不同操作权限、表格怎么不让别人复制粘贴?
1.下方表格名称右键-保护工作表,将所有选项取消勾选 然后设置一个密码就可以了 2.文件旁的三条线点开-选项-安全性,设置编辑权限密码,确定
- 标准非STL容器 : bitset
1. 概念 什么是"标准非STL容器"?标准非STL容器是指"可以认为它们是容器,但是他们并不满足STL容器的所有要求".前文提到的容器适配器stack.que ...
- 巩固javaweb第十天
巩固内容: HTML <meta> 元素 meta标签描述了一些基本的元数据. <meta> 标签提供了元数据.元数据也不显示在页面上,但会被浏览器解析. META 元素通常用 ...
- 到底什么是自动化优先思维?与RPA有什么关系?
基于RPA的自动化优先,正在成为广大组织的主流管理思维 到底什么是自动化优先思维?与RPA有什么关系? 如何用RPA简单快速的打造一个自动化优先的组织? 文/王吉伟 在IT运维项目中,组织经常会遇到先 ...
- A Child's History of England.3
So, Julius Caesar came sailing over to this Island of ours, with eighty vessels and twelve thousand ...
- 【♪♪♪】网易云音乐mp3真实地址
参考别人的博客,得到下面的地址,填上ID号即可,后缀的[.mp3]不用输入 http://music.163.com/song/media/outer/url?id= 例如 最终,合并地址为 http ...
- SpringMVC(4):文件上传与下载
一,文件上传 文件上传是项目开发中最常见的功能之一 ,springMVC 可以很好的支持文件上传,但是SpringMVC上下文中默认没有装配MultipartResolver,因此默认情况下其不能处理 ...
- 浅谈iptables与firewalld防火墙
iptables基于包过滤的防火墙工具 ,Linux 内核集成的 IP 信息包过滤系统,对流入和流出服务器的数据包进行精细管理 规则是存储在专用信息包过滤表中 防火墙按照规则做出判断 而netfilt ...
- 测试数据库并发压力的shell脚本
本节内容:一例用于测试数据库并发压力的shell脚本代码. 例子: #!/bin/bash #********************************# #并发后台运行fun # #for w ...