1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 01:49:41 +01:00
LeetCode/cpp/letter-combinations-of-a-phone-number.cpp

58 lines
1.5 KiB
C++
Raw Normal View History

#include <array>
#include <cassert>
#include <string>
#include <vector>
struct Solution {
std::vector<std::string> letterCombinations(const std::string &digits) {
solver s(digits);
s.solve();
return s.combinations;
}
private:
struct solver {
const std::string &digits;
std::vector<std::string> combinations;
solver(const std::string &digits) : digits(digits) {}
void solve() {
std::string s;
solve(s, 0);
}
private:
std::array<std::string, 8> LETTERS{"abc", "def", "ghi", "jkl",
"mno", "pqrs", "tuv", "wxyz"};
void solve(std::string &s, int i) {
if (i < 0 || i >= static_cast<int>(digits.size())) {
if (!s.empty()) {
combinations.emplace_back(s);
}
return;
}
for (char c : LETTERS[digits[i] - '2']) {
s.push_back(c);
solve(s, i + 1);
s.pop_back();
}
}
};
};
int main() {
Solution s;
assert((s.letterCombinations("23") ==
std::vector<std::string>{"ad", "ae", "af", "bd", "be", "bf", "cd",
"ce", "cf"}));
assert((s.letterCombinations("") == std::vector<std::string>{}));
assert(
(s.letterCombinations("2") == std::vector<std::string>{"a", "b", "c"}));
return 0;
}