forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0017-letter-combinations-of-a-phone-number.cpp
47 lines (42 loc) · 1.28 KB
/
0017-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
/*
Given cell phone pad, return all possible letter combos that the number could represent
Ex. digits = "23" -> ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Hash map all digits to letters, add 1 letter at a time for each digit, then backtrack undo
Time: O(n x 4^n)
Space: O(n x 4^n)
*/
class Solution {
public:
vector<string> letterCombinations(string digits) {
if (digits.empty()) {
return {};
}
unordered_map<char, string> m = {
{'2', "abc"},
{'3', "def"},
{'4', "ghi"},
{'5', "jkl"},
{'6', "mno"},
{'7', "pqrs"},
{'8', "tuv"},
{'9', "wxyz"}
};
string curr = "";
vector<string> result;
dfs(digits, 0, m, curr, result);
return result;
}
private:
void dfs(string digits, int index, unordered_map<char, string>& m, string& curr, vector<string>& result) {
if (index == digits.size()) {
result.push_back(curr);
return;
}
string str = m[digits[index]];
for (int i = 0; i < str.size(); i++) {
curr.push_back(str[i]);
dfs(digits, index + 1, m, curr, result);
curr.pop_back();
}
}
};