17. 電話號碼的字母組合-c++

↑-↑-我-的-仓-鼠-↑-↑發表於2024-05-06

給定一個僅包含數字 2-9 的字串,返回所有它能表示的字母組合。答案可以按 任意順序 返回。

給出數字到字母的對映如下(與電話按鍵相同)。注意 1 不對應任何字母。

示例 1:

輸入:digits = "23"
輸出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2:

輸入:digits = ""
輸出:[]
示例 3:

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

class Solution {
    unordered_map<char,string>phoneMap
    {
        {'2',"abc"},
        {'3',"def"},
        {'4',"ghi"},
        {'5',"jkl"},
        {'6',"mno"},
        {'7',"pqrs"},
        {'8',"tuv"},
        {'9',"wxyz"}
    };
    
public:


    vector<string> letterCombinations(string digits) {
        vector<string>res;
        string re;
        if(digits.empty())
        {
            return res;
        }
        else
        {
            backtrack(digits,0,re,res);
            return res;
        }

    }
    void backtrack(string &digits,int start,string& re,vector<string>& res )
    {
        if(start==digits.size())
        {
            res.push_back(re);
            return;
        }
        else
        {
            char num=digits[start];
            string letters=phoneMap[num];
            for(char letter:letters)
            {
                re.push_back(letter);
                backtrack(digits,start+1,re,res);
                re.pop_back();
            }

        }
    }

};

相關文章