So I was trying to solve LeetCode 17: Letter Combinations of a Phone number. It seemed straightforward to me so I tried this:
class Solution {
public:
std::vector<std::string> answer; // For our answer
std::unordered_map<char, std::vector<char>> keyMap; //Map char range to vec of chars
vector<string> letterCombinations(string digits)
{
//Hanle blanks
if(digits == "") {return {};}
// Generate a map
keyMap['2'] = {'a','b','c'};
keyMap['3'] = {'d','e','f'};
keyMap['4'] = {'g','h','i'};
keyMap['5'] = {'j','k','l'};
keyMap['6'] = {'m','n','o'};
keyMap['7'] = {'p','q','r','s'};
keyMap['8'] = {'t','u','v'};
keyMap['9'] = {'w','x','y','z'};
// If only one digit pressed
if(digits.size() == 1)
{
for(auto& ch: keyMap[digits[0]])
{
answer.push_back(std::string(1,ch));
}
return answer;
}
// Otherwise use backtracking (more like DFS) to build all combinations
backtrack(0,"",digits);
return answer;
}
void backtrack(int index, std::string currentString,std::string digits)
{ //Base case
if(index == digits.size())
{
answer.push_back(currentString);
return;
}
//Recursive case
for(auto ch: keyMap[digits[index]])
{
//currentString += ch;
backtrack(index+1, currentString+ch, digits);
}
}
};```
It resulted in a bottom of the pile solution 😦
What did I miss? I thought I was clever mapping stuff and doing DFS based recursions!!