-
Notifications
You must be signed in to change notification settings - Fork 119
/
17.cpp
77 lines (66 loc) · 1.9 KB
/
17.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
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> ans;
int len = digits.length();
if (len == 0) return ans;
vector<string> letters(len);
string temp;
for (int i = 0; i < digits.length(); i++) {
switch(digits[i]) {
case '2':
letters[i] = "abc";
break;
case '3':
letters[i] = "def";
break;
case '4':
letters[i] = "ghi";
break;
case '5':
letters[i] = "jkl";
break;
case '6':
letters[i] = "mno";
break;
case '7':
letters[i] = "pqrs";
break;
case '8':
letters[i] = "tuv";
break;
case '9':
letters[i] = "wxyz";
break;
default:
break;
}
}
letterCombinationsHelper(ans, temp, 0, letters);
return ans;
}
void letterCombinationsHelper(vector<string> &ans, string &temp, int depth, vector<string> letters) {
if (depth == letters.size()) {
ans.push_back(temp);
return;
}
for (int j = 0; j < letters[depth].size(); j++) {
temp.push_back(letters[depth][j]);
letterCombinationsHelper(ans, temp, depth + 1, letters);
temp.pop_back();
}
}
};
int main() {
string digits = "23";
Solution s;
vector<string> ans = s.letterCombinations(digits);
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << endl;
}
return 0;
}