【LeetCode】电话号码的字母组合

【问题】给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

 示例:

输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。

【思路】这是一个回溯问题的常规模板,我们首先思考回溯的退出条件:我们搜索出来的tmp_res的大小与digits数组大小相同时退出,由于我们每个回溯函数都共用了tmp_res这个变量,因此在函数调用结束后需要恢复为原来的状态,即:
tmp_res += i
backtrace(……)
tmp_res.pop_back()
其中在回溯函数中有两个参数是变化的,一个是搜索出来的字符串,另一个是digits的索引,因为我们是根据digits的数值来选择添加那些字母!!!

class Solution {
public:
    void backtrace(vector<string>& res, string tmp_res, string digits, int idx){  // res为引用形式
        if(tmp_res.length() == digits.length()){
            res.push_back(tmp_res);
            return;
        }
        string str = table[digits[idx]];
        for(auto i: str){
            tmp_res += i;
            backtrace(res, tmp_res, digits, idx+1);
            tmp_res.pop_back();
        }
    }

    vector<string> letterCombinations(string digits) {

        vector<string> res;
        if(digits == "")  return res;
        backtrace(res, "", digits, 0);
        return res;
    }
private:
    unordered_map<char, string> table{{'0', " "}, {'1',"*"}, {'2', "abc"},
            {'3',"def"}, {'4',"ghi"}, {'5',"jkl"},
            {'6',"mno"}, {'7',"pqrs"},{'8',"tuv"},
            {'9',"wxyz"}};
};

猜你喜欢

转载自www.cnblogs.com/zhudingtop/p/11540138.html