17 电话号码的字母组合

#include<iostream>
using namespace std;
#include<vector>
#include<unordered_map>

class Solution
{
public:
    vector<string> letterCombinations(string digits)
    {
        vector<string>combinations;
        if (digits.empty())
        {
            return combinations;
        }

        unordered_map<char, string>aaa
        {
                {'2', "abc"},
                {'3', "def"},
                {'4', "ghi"},
                {'5', "jkl"},
                {'6', "mno"},
                {'7', "pqrs"},
                {'8', "tuv"},
                {'9', "wxyz"}
        };
        string combination;
        backtrack(combinations, aaa, digits, 0, combination);
        return combinations;
    }

    void backtrack(vector<string>& combinations, const unordered_map<char, string>& aaa, const string& digits, int index, string& combination)
    {
        if (index == digits.length())
        {
            combinations.push_back(combination);
        }
        else
        {
            char digit = digits[index];

            string letters = aaa.at(digit);

            for (const char& letter : letters)
            {
                combination.push_back(letter);
                backtrack(combinations, aaa, digits, index + 1, combination);
                combination.pop_back();        //
            }
        }
    }
};

int main()
{
    Solution aaaa;
    string b = "256";
    aaaa.letterCombinations(b);

    system("pause");
    return 0;
}



#include<iostream>
using namespace std;
#include<vector>
#include<unordered_map>

class Solution
{
public:
    vector<string>result;
    string s;
    void backtracking(const string& digits, int index)   //(bbb, 0)
    {
        if (index == digits.size())
        {
            result.push_back(s);
            return;
        }

        //int digit = digits[index];            // 传入的是字符串,要想变为数字需改变
        int digit = digits[index] - '0';        // 将index指向的数字转为int
        string letters = letterMap[digit];      // 取数字对应的字符集

        for (int i = 0; i < letters.size(); i++)
        {
            s.push_back(letters[i]);            // 处理
            backtracking(digits, index + 1);    // 递归,注意index+1,一下层要处理下一个数字了
            s.pop_back();                       // 回溯
        }
    }
private:
    const string letterMap[10] =
    {
        "",
        "",
        "abc",
        "def",
        "ghi",
        "jkl",
        "mno",
        "pqrs",
        "tuv",
        "wxyz",
    };
};

int main()
{
    Solution aaa;
    string bbb = "256";
    aaa.backtracking(bbb, 0);

    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值