mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-14 01:49:41 +01:00
cpp: add «17. Letter Combinations of a Phone Number»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
16283b93e8
commit
4299b5f85a
1 changed files with 57 additions and 0 deletions
57
cpp/letter-combinations-of-a-phone-number.cpp
Normal file
57
cpp/letter-combinations-of-a-phone-number.cpp
Normal file
|
@ -0,0 +1,57 @@
|
||||||
|
#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;
|
||||||
|
}
|
Loading…
Reference in a new issue