-
Notifications
You must be signed in to change notification settings - Fork 0
/
191014-1.cpp
54 lines (51 loc) · 1.11 KB
/
191014-1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/
#include <cstdio>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
vector<string> letterCombinations(string digits) {
static const char* LETTERS[] = { "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
vector<string> res;
int n = digits.size();
if (n > 0) {
vector<const char*> dict;
for (const char* p = digits.c_str(); *p; ++p) {
dict.push_back(LETTERS[*p - '2']);
}
string buf;
buf.resize(n);
vector<const char*> q = dict;
for (;;) {
for (int i = 0; i < n; ++i) {
buf[i] = *q[i];
}
res.push_back(buf);
int i;
for (i = n - 1; i >= 0; --i) {
if (*(++q[i]) == '\0') {
q[i] = dict[i];
} else {
break;
}
}
if (i < 0) break;
}
}
return res;
}
};
void print(const vector<string>& s)
{
printf("[");
for (auto e : s) {
printf(" \"%s\"", e.c_str());
}
printf(" ]\n");
}
int main() {
Solution s;
print(s.letterCombinations("23")); // answer: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
return 0;
}