当前位置:网站首页>leetcode: 17. 电话号码的字母组合
leetcode: 17. 电话号码的字母组合
2022-07-23 09:33:00 【uncle_ll】
17. 电话号码的字母组合
来源:力扣(LeetCode)
链接: https://leetcode.cn/problems/letter-combinations-of-a-phone-number/
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例 1:
输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2:
输入:digits = ""
输出:[]
示例 3:
输入:digits = "2"
输出:["a","b","c"]
提示:
0 <= digits.length <= 4
digits[i] 是范围 ['2', '9'] 的一个数字。
解法
- 递归: 如果digits的长度等于1,映射为字符串后转化为列表;如果长度大于1的话,先递归求前n-1个长度的结果,最后一个数字进行映射;写双重循环进行组合。
- 回溯:首先构建一个哈希表表示电话号码盘,然后基于digits进行回溯,该字符串初始为空。每次取电话号码的一位数字,从哈希表中获得该数字对应的所有可能的字母,并将其中的一个字母插入到已有的字母排列后面,然后继续处理电话号码的后一位数字,直到处理完电话号码中的所有数字,即得到一个完整的字母排列。然后进行回退操作,遍历其余的字母排列。
代码实现
递归
python实现
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits or len(digits) == 0:
return []
mapping = {
'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',
'6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
if len(digits) == 1:
return list(mapping[digits[0]])
prev_letters = self.letterCombinations(digits[:-1])
reverse_letter = mapping[digits[-1]]
return [s + c for s in prev_letters for c in reverse_letter]
c++实现
class Solution {
public:
vector<string> letterCombinations(string digits) {
int n = digits.size();
if (n == 0) return {
};
unordered_map<char, string> maps {
{
'2', "abc"},
{
'3', "def"},
{
'4', "ghi"},
{
'5', "jkl"},
{
'6', "mno"},
{
'7', "pqrs"},
{
'8', "tuv"},
{
'9', "wxyz"}
};
vector<string> res;
if (n == 1) {
string letter = maps[digits[0]];
for (char ch: letter) {
string s;
res.push_back(s+ch);
}
return res;
}
string digits2 = digits.substr(0, n-1);
vector<string> prev_letters = letterCombinations(digits2);
string letter = maps[digits[n-1]];
for (auto prev_letter: prev_letters) {
for (char ch: letter) {
res.push_back(prev_letter+ch);
}
}
return res;
}
};
复杂度分析
- 时间复杂度: O ( 3 m + 4 n ) O(3^m+4^n) O(3m+4n) m是对应3个字母数字个数,n是对应4个字母数字的个数,不同的字母组合一共有 3 m × 4 n 3^m \times 4^n 3m×4n种,需要遍历每一种字母组合。
- 空间复杂度: O ( m + n ) O(m+n) O(m+n)
回溯
python实现
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits or len(digits) == 0:
return []
letters = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
}
res = []
n = len(digits)
def helper(path, depth):
if depth == n:
res.append(''.join(path))
return
string = letters[digits[depth]]
for ch in string:
path.append(ch)
helper(path, depth+1)
path.pop()
helper([], 0)
return res
c++实现
class Solution {
vector<string> res;
unordered_map<char, string> maps {
{
'2', "abc"},
{
'3', "def"},
{
'4', "ghi"},
{
'5', "jkl"},
{
'6', "mno"},
{
'7', "pqrs"},
{
'8', "tuv"},
{
'9', "wxyz"}
};
public:
void helper(vector<char> path, int depth, string digits,vector<string>& res, unordered_map<char, string> maps) {
if (depth == digits.size()) {
string tmp;
for (auto ch: path) {
tmp += ch;
}
res.push_back(tmp);
return ;
}
string letters = maps[digits[depth]];
for (int i=0; i<letters.size(); i++) {
char ch = letters[i];
path.push_back(ch);
helper(path, depth+1, digits, res, maps);
path.pop_back();
}
}
vector<string> letterCombinations(string digits) {
if (digits.size() == 0)
return {
};
helper({
}, 0, digits, res, maps);
return res;
}
};
复杂度分析
- 时间复杂度: O ( 3 m + 4 n ) O(3^m+4^n) O(3m+4n) m是对应3个字母数字个数,n是对应4个字母数字的个数,不同的字母组合一共有 3 m × 4 n 3^m \times 4^n 3m×4n种,需要遍历每一种字母组合。
- 空间复杂度: O ( m + n ) O(m+n) O(m+n)
参考
边栏推荐
- 对象使用过程中背后调用了哪些方法
- Openharmony South learning notes - hi3861+hc-sr04 ultrasonic testing
- The self-developed data products have been iterated for more than a year. Why not buy third-party commercial data platform products?
- 工作小记:一次抓包
- 【测试平台开发】二十、完成编辑页发送接口请求功能
- Design and implementation of websocket universal packaging
- Qt文档阅读笔记-Audio Example解析
- Qt| imitation text floating letter
- [array & String & Macro exercise]
- 固定资产管理系统哪家好?固定资产管理平台有哪些?
猜你喜欢

【刷题记录】19. 删除链表的倒数第 N 个结点

什么是Per-Title编码?

【数组&&字符串&&宏练习题】

Zhongwang CAD professional 2022 software installation package download and installation tutorial
![[WinForm] desktop program implementation scheme for screenshot recognition and calculation](/img/9f/e67af4386cff9febf0fb5203da03f0.jpg)
[WinForm] desktop program implementation scheme for screenshot recognition and calculation

OpenCV计算外包矩形

Using shell script to block IP with high scanning frequency

Work notes: one time bag grabbing

Cmake notes

C language project practice: 24 point game calculator (based on knowledge points such as structure, pointer, function, array, loop, etc.)
随机推荐
Qt| imitation text floating letter
【无标题】
QT document reading notes audio example analysis
[interview frequency] cookies, sessions, tokens? Don't worry about being asked after reading it
[test platform development] 21. complete sending interface request and display response header information
Detailed tutorial of typora drawing bed configuration
微信官方出品!小程序自动化框架 minium 分享预告
运维高级作业03
云呐-如何加强固定资产管理?怎么加强固定资产管理?
【数组&&字符串&&宏练习题】
CSDN写文方法(二)
Authing supports Zadig! Unified authentication and rapid docking of cloud native users
First acquaintance and search set
C language implementation of classroom random roll call system
LZ77 file compression
右键新建txt,新建文本文件不见了,通过添加注册表就可以解决,找来找去办法解决不了的终极办法
直播课堂系统02-搭建项目环境
【无标题】测试【无标题】测试
Advanced operation and maintenance 02
win11安装系统提示virtualBox不兼容需要卸载virtual的解决办法,但是卸载列表找不到virtual的解决办法