LeetCode17. 电话号码的字母组合(2024秋季每日一题 59)

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例 1:

输入:digits = "23"

输出:"ad","ae","af","bd","be","bf","cd","ce","cf"

示例 2:

输入:digits = ""

输出:\[\]

示例 3:

输入:digits = "2"

输出:"a","b","c"

提示:

0 < = d i g i t s . l e n g t h < = 4 0 <= digits.length <= 4 0<=digits.length<=4

digitsi 是范围 '2', '9' 的一个数字。


思路:

  • 根据给定的数字键,遍历数字,枚举对应位置的字母
  • 如果遍历到最后一个数字,则将当前这个字符串加入最终的答案
  • 返回最终的字符串集合
cpp 复制代码
class Solution {
public:
    unordered_map<int, string> h;
    vector<string> res;
    vector<string> letterCombinations(string digits) {
        if(digits.size() == 0) return res;
        h[2] = "abc";
        h[3] = "def";
        h[4] = "ghi";
        h[5] = "jkl";
        h[6] = "mno";
        h[7] = "pqrs";
        h[8] = "tuv";
        h[9] = "wxyz";
        dfs(digits, 0, "");
        return res;
    }
    void dfs(string s, int d, string ans){
        if(s.size() == ans.size()){
            res.push_back(ans);
            return;
        }
        for(auto &c: h[s[d] - '0']){
            dfs(s, d + 1, ans + c);
        }
    }
};
相关推荐
淡海水5 分钟前
08-03-不可变-ImmutableDictionary-TKey-TValue-与ImmutableHashSet-T-持久化哈希树
数据结构·算法·c#·哈希算法·dictionary·immutable
hansang_IR9 分钟前
【题解】[APIO2023] 赛博乐园 / cyberland
c++·算法·图论
洛阳纸贵39 分钟前
MATLAB-matlab基础知识
学习·算法·matlab
落羽的落羽44 分钟前
【AI】快速理解AI应用的相关名词概念
linux·c++·人工智能·python·计算机网络·算法
Nil2081 小时前
leetcode 17电话号码的字母组合
算法·leetcode·职场和发展
203号居民3 小时前
LeetCode hot 100 — 25. K 个一组翻转链表
算法·leetcode·链表
ocean21033 小时前
2025-2026年AI算法与模型研发面试高频知识点洞察
人工智能·算法·面试
Nil2083 小时前
leetcode 78子集
数据结构·算法·leetcode
en.en..4 小时前
Linux fork() 工作原理
数据结构·算法
地平线开发者5 小时前
bevformer算法模型详细解读
算法