LeetCode 17. 电话号码的字母组合

题目

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

思路

比较简单的一个回溯,有手就行。。。。

代码

class Solution {
public:

    void getPhoneMap(unordered_map<char, string>& phoneMap) 
    {
        phoneMap['2'] = "abc";
        phoneMap['3'] = "def";
        phoneMap['4'] = "ghi";
        phoneMap['5'] = "jkl";
        phoneMap['6'] = "mno";
        phoneMap['7'] = "pqrs";
        phoneMap['8'] = "tuv";
        phoneMap['9'] = "wxyz";
    };

    void backtrack(std::vector<string>& res,const unordered_map<char, string>& phoneMap,int index,string digits, std::string  digitString)
    {
        if(index == digits.length())
        {
            res.push_back(digitString);
        }
        else
        {
            char d = digits[index];
            const string& letters = phoneMap.at(d);
            for(const auto& letter:letters)
            {
                digitString.push_back(letter);
                backtrack(res, phoneMap, index+1, digits, digitString );
                digitString.pop_back();
            }
        }
    }
    
    vector<string> letterCombinations(string digits)
    {
        std::vector<string> res;
        if(digits.length() == 0)
            return res;

        unordered_map<char, string> phoneMap;
        getPhoneMap(phoneMap);

        std::string digitString;
        backtrack(res, phoneMap, 0, digits, digitString);

        return res;
    }
};

你可能感兴趣的:(C++算法与数据结构,c++,leetcode)