leetcode 17 电话号码的字母组合

时间:2021-08-20
本文章向大家介绍leetcode 17 电话号码的字母组合,主要包括leetcode 17 电话号码的字母组合使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

其实递归不难,出现错误的方面主要是变量的作用范围和循环的终止条件,比如对于已经写入了一个‘a’,在写入下一位的时候,递归函数的形参应当保持为‘a’,这要求每次循环中都将所用的变量更新为‘a’。第二个是终止条件,该例中不能说是终止条件,只能说是输入位数等于1时,代表后面已经没有数位了,不需要再进行循环,这时不能在循环中写入return,因为这样会导致,循环了一次,直接return了,后面的情况咋办?所以自然退出循环,不进入下一层递归,自然return就好了。贴代码

class Solution {
private:
    vector<string> res;
    vector<string> ch =
    {
        "",
        "",
        "abc",
        "def",
        "ghi",
        "jkl",
        "mno",
        "pqrs",
        "tuv",
        "wxyz",
    };
public:
    vector<string> letterCombinations(string digits) 
    {
        string res_temp;
        if(!digits.length())
        return res;
        construct(digits,res_temp);
        return res;        
    }
    void construct(string digits,string temp)
    {
        int a = digits[0] - '0';
        for(auto temp_ch:ch[a])
        {
            string res_temp = temp;
            res_temp.insert(res_temp.length(),1,temp_ch);
            if(digits.length()>1)
            construct(digits.substr(1,digits.length()-1),res_temp);
            else
            {
                res.push_back(res_temp);
            }
        }
        return;
    }
};

原文地址:https://www.cnblogs.com/zhaohhhh/p/15166423.html