当前位置:网站首页>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)
参考
边栏推荐
- 基本51单片机点阵汉字显示程序设计
- QT document reading notes audio example analysis
- 【刷题记录】19. 删除链表的倒数第 N 个结点
- 2022河南萌新联赛第(二)场:河南理工大学 补题题解
- The pit trodden by real people tells you to avoid the 10 mistakes often made in automated testing
- Which is a good fixed asset management system? What are the fixed asset management platforms?
- win11安装系统提示virtualBox不兼容需要卸载virtual的解决办法,但是卸载列表找不到virtual的解决办法
- LeetCode-227-基本计算器||
- 【无标题】
- [WinForm] desktop program implementation scheme for screenshot recognition and calculation
猜你喜欢
![[test platform development] 21. complete sending interface request and display response header information](/img/53/42411ceb6e0e304355ddc396ea2922.png)
[test platform development] 21. complete sending interface request and display response header information

转自玉溪信息公开:mRNA新冠疫苗、九洲马破伤风免疫球蛋白等产品有望年内上市。

Feignclient utilise un tutoriel détaillé (illustration)
It is suggested that Siyuan notes can be compatible with third-party sync disks

PKI体系快速介绍
![[can I do your first project?] Detailed introduction and Simulation Implementation of gzip](/img/92/dfef5887e2313f8025baf11c8f4379.png)
[can I do your first project?] Detailed introduction and Simulation Implementation of gzip

win11安装系统提示virtualBox不兼容需要卸载virtual的解决办法,但是卸载列表找不到virtual的解决办法
![[array & String & Macro exercise]](/img/44/26debc1ee958277935e73a75d894d4.png)
[array & String & Macro exercise]

String function of MySQL function summary

Using shell script to block IP with high scanning frequency
随机推荐
Is it risky and safe to open an account for stock speculation?
First acquaintance and search set
C language introduction practice (11): enter a group of positive integers and sum the numbers in reverse order
After using vscode to format the code, save and find that the code is messy again. What should I do? Vs remove formatting
It is suggested that Siyuan notes can be compatible with third-party sync disks
ArgoCD 用户管理、RBAC 控制、脚本登录、App 同步
固定资产管理系统哪家好?固定资产管理平台有哪些?
[test platform development] XVII. The interface editing page realizes the drop-down cascade selection, and binds the module to which the interface belongs
基本51单片机点阵汉字显示程序设计
@FeignClient使用詳細教程(圖解)
Introduction and mechanism of Aptos
运维高级作业03
Quick introduction to PKI system
452. Detonate the balloon with the minimum number of arrows
About flex layout justify content: the last solution to the misalignment of space around and why it is solved like this is a discussion
正则表达式常用语法解析
452. 用最少数量的箭引爆气球
4. Find the median of two positive arrays
Towhee weekly model
C# 线程锁和单多线程简单使用