LeetCode/cpp/letter-combinations-of-a-phone-number.cpp

58 lines
1.5 KiB
C++
Raw Permalink 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;
}