[LeetCode] Letter Combinations of a Phone Number

本文介绍了一种通过深度优先遍历算法解决电话号码数字到字母所有可能组合的问题。使用递归方式,结合数字与字母的映射表,实现快速生成所有组合。

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

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"].

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

该题的主要意思:给你2-9数字中的任意几个,其中每个数字都包含三个字母,其所包含的字母如上图所示,求出这些数字所构成的所有组合。

该种题型较为简单,我们可以通过深度优先遍历求解。

深度优先遍历算法如下:

复杂度:时间 O(n2)递归栈空间

思路:首先建一个表,来映射号码和字母的关系。然后对号码进行深度优先搜索,对于每一位,从表中找出数字对应的字母,这些字母就是本轮搜索的几种可能。

char str[1000];
vector<string>result;
class Solution {
public:
    vector<string> letterCombinations(string digits) {
        int len = digits.size();
        if (len == 0)
            return result;
        string nums[] = {" ", " ", "ab", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        digitsDeal(digits, 0, len, nums);
        return result;
    }
public:
    void digitsDeal(string &digits, int i, int len, string *nums)
    {
        if(i == len)
        {
            str[len] = '\0';
            string temp = str;
            result.push_back(temp);
            return;
        }

        int index = digits[i]-'0';
        for(int  j= 0; j < nums[index].size(); ++j)
        {
            str[i] = nums[index][j];
            digitsDeal(digits, i+1, len, nums);
        }
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值