-
Notifications
You must be signed in to change notification settings - Fork 0
/
letter_combinations_of_a_phone_number.cpp
47 lines (41 loc) · 1.29 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
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> result;
unordered_map<char, vector<char>> dmap;
dmap['2'] = {'a', 'b', 'c'};
dmap['3'] = {'d', 'e', 'f'};
dmap['4'] = {'g', 'h', 'i'};
dmap['5'] = {'j', 'k', 'l'};
dmap['6'] = {'m', 'n', 'o'};
dmap['7'] = {'p', 'q', 'r', 's'};
dmap['8'] = {'t', 'u', 'v'};
dmap['9'] = {'w', 'x', 'y', 'z'};
core(digits, 0, dmap, result, string());
return result;
}
void core(string& digits, int index,
unordered_map<char, vector<char>>& dmap,
vector<string>& result, string str)
{
typedef vector<char>::iterator vcit;
char ch = digits[index];
if (ch < '2' && ch > '9')
{
result.clear();
return;
}
if (index == digits.size() - 1)
{
for (vcit it = dmap[ch].begin(); it != dmap[ch].end(); ++it)
{
result.push_back(string(str + *it));
}
return;
}
for (vcit it = dmap[ch].begin(); it != dmap[ch].end(); ++it)
{
core(digits, index + 1, dmap, result, str + *it);
}
}
};