LeetCode 17. 电话号码的字母组合(C++)

本文介绍了一个基于回溯算法实现的电话号码数字到字母的转换问题。通过递归地构建所有可能的字母组合来解决该问题,并提供了一段C++代码示例。该算法适用于长度在0到4之间的输入字符串,并且只考虑了从'2'到'9'的数字。

(思路:回溯实现排列组合)

1.题目如下:

在这里插入图片描述

示例 1:

输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]

示例 2:

输入:digits = ""
输出:[]

示例 3:

输入:digits = "2"
输出:["a","b","c"]

提示:

0 <= digits.length <= 4
digits[i] 是范围 ['2', '9'] 的一个数字。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/letter-combinations-of-a-phone-number

2.代码如下:

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> combinations;
        //如果为0,直接返回
        if(digits.length()==0){
            return combinations;
        }
        //用字典存储每个按键对应的字母
        unordered_map<char,string> numbers{
                {'2', "abc"},
                {'3', "def"},
                {'4', "ghi"},
                {'5', "jkl"},
                {'6', "mno"},
                {'7', "pqrs"},
                {'8', "tuv"},
                {'9', "wxyz"}
        };
        
        string combination;
        backTrack(combinations,numbers,0,digits,combination);
        return combinations;
    }
    void backTrack(vector<string> &combinations,const unordered_map<char,string> numbers,int index,const string& digits,string& combination){
   	 	//index==digits.length()代表遍历到了指定长度的几个字母,作为一个结果存储
        if(index==digits.length()){
           combinations.push_back(combination);
        }
        else{
            char digit=digits[index];
            const string& letters=numbers.at(digit);
            //遍历letters,相当于广度遍历树
            for(const char&x:letters){
            	//放树树这一层的一个分支
                combination.push_back(x);
                //向下一层遍历
                backTrack(combinations,numbers,index+1,digits,combination);
                //撤回原来的分支,为了加入同一层的下一个分支再向下
                combination.pop_back();
            }

        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_panbk_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值