LeetCode第17题:Letter Combinations of a Phone Number(C++详解)

本文解析了LeetCode上一道经典题目:电话号码的字母组合。通过递归思想和暴力破解的方法,实现了从2-9的数字转换为其可能的所有字母组合,详细介绍了代码实现过程及性能分析。

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

  1. Letter Combinations of a Phone Number
    Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.
在这里插入图片描述
Example:

Input: “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.

题目解析:
题目就是字母排列组合,大家学过排列组合的想必都知道,看到题目直观感受就是暴力组合。

代码:

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res,tempRes;//返回结果
        int length = digits.size();//输入长度
        if(length == 0)
        {
            return vector<string>();//只能返回[],不能返回"",不然无法通过测试
        }
        res.push_back("");//初始化
        string tempStr;
        map<char, vector<char>> dic;//输入号码字符集
        dic.insert(pair<char, vector<char>>('1', {}));
	    dic.insert(pair<char, vector<char>>('2', {'a','b','c'}));
	    dic.insert(pair<char, vector<char>>('3', {'d','e','f'}));
	    dic.insert(pair<char, vector<char>>('4', {'g','h','i'}));
	    dic.insert(pair<char, vector<char>>('5', {'j','k','l'}));
	    dic.insert(pair<char, vector<char>>('6', {'m','n','o'}));
	    dic.insert(pair<char, vector<char>>('7', {'p','q','r','s'}));
	    dic.insert(pair<char, vector<char>>('8', {'t','u','v'}));
	    dic.insert(pair<char, vector<char>>('9', {'w','x','y','z'}));
        for(int i=0;i<length;i++)
        {
            int resLen = res.size();
            tempRes.clear();//每次执行完,必须清零
            vector<char> charList = dic[digits[i]];
            for(int j=0;j<resLen;j++)
            {
                tempStr = res[j];
                for(int k=0;k<charList.size();k++)
                {
                    tempRes.push_back(tempStr + charList[k]);
                }
            }
            res = tempRes;//相当于递归
        }
        return res;
    }
};

特别说明:
for循环中采用了tempRes来获取最终的结果,相当于遍历出所有结果,例如:我们代码中res初始化为{""};第一次遍历的时候tempRes即为digits中第一个数值代表的字母集合,如果第一个数值是2的话,此时tempRes即为{‘a’,‘b’,‘c’},赋值给res;然后进行第二次遍历,获取第二个数值代表的字母集合,重新push到tempRes中,所以每次遍历tempRes必须清零,tempRes.clear()

代码性能:
在这里插入图片描述

总结:最近忙新接手新项目,在新环境接受新挑战,写博客的频率,有所降低,一时反应偏慢,还得坚持,逆水行舟,不进则退,继续加油,坚持写博;上述代码属于暴力破解,递归思想,使用内存空间较多,不建议使用,大家有好的方法,欢迎给个链接。谢谢大家。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值