Letter Combinations of a Phone Number

本文介绍了一种用于将数字字符串转换为对应字母组合的方法,包括遍历法和树搜索法,适用于电话按钮上的数字到字母映射。

1. Question

给一个数字字符串,按照电话上各个数字对应的字母,返回该字符串代表的所有可能的字母组合。

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.



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

2. Solution(O(3n))

考虑特殊情况:

  • 空串

2.1 遍历法

依次遍历字符串中的每个数,寻找可能的组合。

    public List<String> letterCombinations( String digits ){
        String[] map = { " ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        int len = digits.length();
        LinkedList<String> res = new LinkedList<String>();
        if( len<1 )
            return res;
        res.add("");
        for( int i=0; i<len; i++ ){
            int now = digits.charAt( i ) - '0';
            if( now<2 )
                continue;
            char[] toInsert = map[now].toCharArray();
            while( res.peek().length() == i ) {
                String each = res.remove();
                for( int j=0; j<toInsert.length; j++ )
                    res.add( each + toInsert[j] );
            }
        }
        return res;
    }
View Code
2.2 树搜索法

对数字进行解析,相当于遍历一棵树,可以使用数的遍历算法

public List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<String>();
        String[] map = new String[10];
        map[0] = "";
        map[1] = "";
        map[2] = "abc";
        map[3] = "def";
        map[4] = "ghi";
        map[5] = "jkl";
        map[6] = "mno";
        map[7] = "pqrs";
        map[8] = "tuv";
        map[9] = "wxyz";
        char[]    middleTemp = new char[digits.length()];
        dfsGetStr(digits, 0, middleTemp, map, result); 
        return result;
    }
    
    private void dfsGetStr(String digits,int index, 
            char[] middleStr, String[] map, List<String> result) {
        if(index == digits.length()) {
            result.add(new String(middleStr));
            return ;
        }
        char strChar = digits.charAt(index);
        for(int i=0; i<map[strChar-'0'].length(); i++) {
            middleStr[index] = map[strChar-'0'].charAt(i);
            dfsGetStr(digits, index+1, middleStr, map, result);
        }
    }
View Code

 

posted on 2015-07-03 23:05 HF_Cherish 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/hf-cherish/p/4607097.html

这段代码是 **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、付费专栏及课程。

余额充值