forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathletter-combinations-of-a-phone-number.cpp
76 lines (69 loc) · 2.27 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
// Time: O(n * 4^n)
// Space: O(n)
// Iterative solution.
class Solution {
public:
/**
* @param digits A digital string
* @return all posible letter combinations
*/
vector<string> letterCombinations(string& digits) {
if (digits.empty()) {
return {};
}
vector<string> result = {""};
vector<string> lookup = {"", "", "abc", "def",
"ghi", "jkl", "mno",
"pqrs", "tuv", "wxyz"};
for (int i = digits.size() - 1; i >= 0; --i) {
const string& choices = lookup[digits[i] - '0'];
const int n = result.size(), m = choices.length();
for (int j = n; j < m * n; ++j) {
result.emplace_back(result[j % n]);
}
for (int j = 0; j < m * n; ++j) {
result[j].insert(result[j].end(), choices[j / n]);
}
}
for (auto& s : result) {
reverse(s.begin(), s.end());
}
return result;
}
};
// Time: O(n * 4^n)
// Space: O(n)
// Recursion solution.
class Solution2 {
public:
/**
* @param digits A digital string
* @return all posible letter combinations
*/
vector<string> letterCombinations(string& digits) {
if (digits.empty()) {
return {};
}
vector<string> result = {};
vector<string> lookup = {"", "", "abc", "def",
"ghi", "jkl", "mno",
"pqrs", "tuv", "wxyz"};
string combination;
int len = 0;
letterCombinationsRecu(digits, lookup, &combination, &len, &result);
return result;
}
void letterCombinationsRecu(const string& digits, vector<string>& lookup,
string *combination,
int *len, vector<string> *result) {
if (*len == digits.size()) {
result->emplace_back(*combination);
} else {
for (const auto& c : lookup[digits[*len] - '0']) {
combination->insert(combination->end(), c), ++(*len);
letterCombinationsRecu(digits, lookup, combination, len, result);
combination->pop_back(), --(*len);
}
}
}
};