Problem P28. [算法课回溯] 电话号码的字母组合

回溯,唯一麻烦的是要建立一个字典,键值对为数字字符对应英文字符串

#include<iostream>
#include<bits/stdc++.h>
#include<cstdio>
#include<string>

using namespace std;

void backtrack(vector<string>& combinations, const unordered_map<char, string>& phoneMap, const string& digits, int index, string& s) {
    if (index == digits.length()) {
        combinations.push_back(s);
    } else {
        char digit = digits[index];
        const string& letters = phoneMap.at(digit);
        for (const char& letter: letters) {
            s.push_back(letter);
            backtrack(combinations, phoneMap, digits, index+1, s);
            s.pop_back();
        }
    }
}

int main()
{
    string digits;
    cin >> digits;
    vector<string> combinations;
    if (digits.empty()) {
        cout << "[]";
        return 0;
    }
    unordered_map<char, string> phoneMap {
        {'2', "abc"},
        {'3', "def"},
        {'4', "ghi"},
        {'5', "jkl"},
        {'6', "mno"},
        {'7', "pqrs"},
        {'8', "tuv"},
        {'9', "wxyz"}
    };
    string s;
    backtrack(combinations, phoneMap, digits, 0, s);
    cout << '[';
    for (int i = 0; i < combinations.size(); i++) {
        cout << combinations[i];
        if (i < combinations.size()-1) {
            cout << ',';
            cout << ' ';
        }
    }
    cout << "]";
    return 0;
}

posted @ 2022-10-15 13:53  白缺  阅读(63)  评论(0编辑  收藏  举报