mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
58 lines
1.5 KiB
C++
58 lines
1.5 KiB
C++
|
#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;
|
||
|
}
|