回溯,唯一麻烦的是要建立一个字典,键值对为数字字符对应英文字符串
#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;
}
标签:digits,index,const,string,phoneMap,combinations,字母组合,Problem,P28
From: https://www.cnblogs.com/understanding-friends/p/16794080.html