Letter Combinations of a Phone Number

本文介绍了一种算法,该算法能够根据电话按键上数字到字母的映射,输入一个数字字符串并返回所有可能的字母组合。通过深度优先搜索(DFS)递归地构建所有可能的组合。

Letter Combinations of a Phone Number

Given a digit string, 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.

Example:

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

 

Code:

class Solution {
public:
    map<char,vector<char>> dict;
    vector<string> ret;
    void CreateDict()
    {
        dict.clear();
        dict['2'].push_back('a');
        dict['2'].push_back('b');
        dict['2'].push_back('c');
        dict['3'].push_back('d');
        dict['3'].push_back('e');
        dict['3'].push_back('f');
        dict['4'].push_back('g');
        dict['4'].push_back('h');
        dict['4'].push_back('i');
        dict['5'].push_back('j');
        dict['5'].push_back('k');
        dict['5'].push_back('l');
        dict['6'].push_back('m');
        dict['6'].push_back('n');
        dict['6'].push_back('o');
        dict['7'].push_back('p');
        dict['7'].push_back('q');
        dict['7'].push_back('r');
        dict['7'].push_back('s');
        dict['8'].push_back('t');
        dict['8'].push_back('u');
        dict['8'].push_back('v');
        dict['9'].push_back('w');
        dict['9'].push_back('x');
        dict['9'].push_back('y');
        dict['9'].push_back('z');


    }
    
    void DFS(int curDep,int len,string &s,string ans)
    {
        if(curDep==len)
        {
            ret.push_back(ans);
            return ;
        }
        for(int i=0;i<dict[s[curDep]].size();i++)
            DFS(curDep+1,len,s,ans+dict[s[curDep]][i]);
    }
    
    vector<string> letterCombinations(string digits) {
        ret.clear();
        CreateDict();
        DFS(0,digits.size(),digits,"");
        return ret;
    }
};


 

这段代码是 **LeetCode 第 17 题:电话号码的字母组合(Letter Combinations of a Phone Number)** 的标准 **回溯法(Backtracking)** 解法。它使用递归回溯的方式生成所有可能的字母组合。 --- ## ✅ VS2022 可运行版本(完整代码) 以下是在 **Visual Studio 2022 (VS2022)** 中可以直接运行的完整版本,包含 `main()` 函数和测试输入。 ```cpp #include <iostream> #include <vector> #include <string> #include <unordered_map> using namespace std; class Solution { public: vector<string> letterCombinations(string digits) { vector<string> combinations; if (digits.empty()) { return combinations; } unordered_map<char, string> phoneMap{ {'2', "abc"}, {'3', "def"}, {'4', "ghi"}, {'5', "jkl"}, {'6', "mno"}, {'7', "pqrs"}, {'8', "tuv"}, {'9', "wxyz"} }; string combination; backtrack(combinations, phoneMap, digits, 0, combination); return combinations; } void backtrack(vector<string>& combinations, const unordered_map<char, string>& phoneMap, const string& digits, int index, string& combination) { if (index == digits.length()) { combinations.push_back(combination); } else { char digit = digits[index]; const string& letters = phoneMap.at(digit); for (const char& letter : letters) { combination.push_back(letter); // 选择当前字母 backtrack(combinations, phoneMap, digits, index + 1, combination); // 递归到下一层 combination.pop_back(); // 回溯,撤销选择 } } } }; // 测试函数 int main() { Solution sol; string digits; cout << "请输入电话号码(仅包含数字2-9): "; cin >> digits; for (char c : digits) { if (c < '2' || c > '9') { cout << "输入包含非法字符!只允许数字 2 到 9。" << endl; return 1; } } vector<string> result = sol.letterCombinations(digits); cout << "所有可能的字母组合为:" << endl; for (const string& s : result) { cout << s << endl; } return 0; } ``` --- ## ✅ 示例输入输出 ### 示例输入: ``` 请输入电话号码(仅包含数字2-9): 23 ``` ### 输出: ``` 所有可能的字母组合为: ad ae af bd be bf cd ce cf ``` --- ## ✅ 代码说明 | 步骤 | 功能说明 | |------|----------| | 1. `letterCombinations` | 主函数,初始化组合并调用回溯函数 | | 2. `phoneMap` | 存储数字到字母的映射 | | 3. `backtrack` | 回溯函数,递归生成所有组合 | | 4. `combination` | 当前路径的字符串 | | 5. `push_back/pop_back` | 添加和撤销选择,实现回溯 | --- ## ✅ 时间复杂度分析 假设每个数字平均对应 3 个字母,数字长度为 `n`: - 总共的组合数为:`3^n` 或 `4^n`(取决于数字) - 每次组合的长度为 `n` - 所以总时间复杂度为:**O(3^n × n)** 或 **O(4^n × n)** 空间复杂度主要是递归栈和临时字符串的空间,为:**O(n)** --- ## ✅ 常见问题排查(VS2022) 1. **编译错误**: - 确保项目设置为 **C++11 或更高标准**。 - 检查是否包含头文件 `<vector>`、`<string>`、`<unordered_map>`。 2. **运行时崩溃**: - 确保输入的字符串 `digits` 不为空。 - 确保只输入了数字 2-9。 3. **无输出**: - 输入为空字符串,返回空结果是正常的。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值