forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathletter-combinations-of-a-phone-number.cpp
85 lines (78 loc) · 2.45 KB
/
letter-combinations-of-a-phone-number.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Time: O(n * 4^n)
// Space: O(1)
// iterative solution
class Solution {
public:
vector<string> letterCombinations(string digits) {
static const vector<string> lookup = {" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
if (empty(digits)) {
return {};
}
int total = 1;
for (const auto& digit : digits) {
total *= size(lookup[digit - '0']);
}
vector<string> result;
for (int i = 0; i < total; ++i) {
int base = total;
string curr;
for (const auto& digit : digits) {
const auto& choices = lookup[digit - '0'];
base /= size(choices);
curr.push_back(choices[(i / base) % size(choices)]);
}
result.emplace_back(move(curr));
}
return result;
}
};
// Time: O(n * 4^n)
// Space: O(1)
// iterative solution
class Solution2 {
public:
vector<string> letterCombinations(string digits) {
static const vector<string> lookup = {" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
if (empty(digits)) {
return {};
}
vector<string> result = {""};
for (int i = size(digits) - 1; i >= 0; --i) {
const auto& choices = lookup[digits[i] - '0'];
int m = size(choices), n = size(result);
result.resize(m * n);
for (int j = m * n - 1; j >= 0; --j) {
result[j] = choices[j / n] + result[j % n];
}
}
return result;
}
};
// Time: O(n * 4^n)
// Space: O(n)
// recursive solution
class Solution3 {
public:
vector<string> letterCombinations(string digits) {
if (empty(digits)) {
return {};
}
vector<string> result;
string curr;
letterCombinationsRecu(digits, &curr, &result);
return result;
}
private:
void letterCombinationsRecu(const string &digits, string *curr, vector<string> *result) {
static const vector<string> lookup = {" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
if (size(*curr) == size(digits)) {
result->emplace_back(*curr);
return;
}
for (const auto& c: lookup[digits[size(*curr)] - '0']) {
curr->push_back(c);
letterCombinationsRecu(digits, curr, result);
curr->pop_back();
}
}
};