Created
June 4, 2020 01:00
-
-
Save bhaveshmunot1/fc21906ace5b2d49d4b2a1afdb412a27 to your computer and use it in GitHub Desktop.
Leetcode #17: Letter Combinations of a Phone Number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
map<char, string> numToString = {{'2', "abc"}, {'3', "def"}, {'4', "ghi"}, | |
{'5', "jkl"}, {'6', "mno"}, {'7', "pqrs"}, | |
{'8', "tuv"}, {'9', "wxyz"}}; | |
vector<string> answer; | |
string input; | |
void recurse(string path, int index) { | |
if (!(index < input.length())) { // the entire string is processed already. | |
if (!path.empty()) { // only add non-empty strings. | |
answer.push_back(path); // add the current value in final answer. | |
} | |
return; // nothing else to do here. | |
} | |
char currentChar = input[index]; | |
string possibilities = numToString[currentChar]; | |
for (char c: possibilities) { // for each possibility. | |
path.push_back(c); // assume current possibility. | |
recurse(path, index+1); // recursively solve the remaining problem. | |
path.pop_back(); // undo the current possibility. | |
} | |
} | |
vector<string> letterCombinations(string digits) { | |
input = digits; | |
recurse("", // empty string in the beginning. | |
0); // what index in input to start the recursion. | |
return answer; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment