LeetCode - 17. Letter Combinations of a Phone Number - C++

本文深入解析了电话号码字母组合问题的两种解决方案,通过递归深度优先搜索(DFS)和迭代方法,详细展示了如何将数字转换为可能的字母组合。使用数组作为映射表,巧妙地处理了数字到字母的映射过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

借鉴的这个博客,理解之后改为自己的风格

解法一

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> result;
        if(digits.empty()) return result;
        string dictionary[] = {"", "",
                               "abc", "def", "ghi", "jkl",
                               "mno", "pqrs", "tuv", "wxyz"};
        letterCombinationDFS(digits, dictionary, 0, "", result);
        return result; 
    }
    
    void letterCombinationDFS(string digits, string dictionary[], 
                            int level, string current, 
                            vector<string>& result) {
        
        if(level == digits.size()) {
            result.push_back(current);
            return;
        } 
        
        string s = dictionary[digits[level]-'0'];
        
        for(int i=0; i<s.size(); i++) {
            
            letterCombinationDFS(digits, dictionary, 
                                 level+1, current+s[i], result);
        }          
    }
};

解法二

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        if (digits.empty()) return {};
        vector<string> result{""};
        
        string dictionary[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        
        for (int i = 0; i < digits.size(); i++) {
            vector<string> temp;
            string s = dictionary[digits[i] - '0'];
            for (int j=0; j<result.size(); j++) {
                for (int k=0; k<s.size(); k++) {
                    temp.push_back(result[j] + s[k]);
                }
            }
            result = temp;
        }
        return result;
    }
};

用数组作map,访问的时候 -‘0’,挺妙的。

没什么好说的,题挺规矩,自己做不出,多练。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值