Thursday, August 3rd

 Phone number names

Given a string of digits, return all possible letter combinations based on the mapping of numbers to letters on a telephone



The above phone was found on Wikipedia, attributed to Takuya!commonswiki, under the Create Commons license.  No changes were make

This problem builds on the backtracking problems of the previous 2 days.  By looking at the problem constraints, where the maximum input string is of length 4, we can see that a brute-force backtracking approach would be appropriate.

Even though we're dealing with numbers, the problem gives us numbers as a string.  So we begin by mapping the digit characters to the letters on a phone.  We keep the hashmap as a global variable to avoid passing too many variables to the recursive function.

unordered_map<int,string> hashmap;

    hashmap.insert(make_pair('2',"abc"));
hashmap.insert(make_pair('3',"def"));
hashmap.insert(make_pair('4',"ghi"));
hashmap.insert(make_pair('5',"jkl"));
hashmap.insert(make_pair('6',"mno"));
hashmap.insert(make_pair('7',"pqrs"));
hashmap.insert(make_pair('8',"tuv"));
hashmap.insert(make_pair('9',"wxyz"));

Next we design our backtracking function.  From previous days, we know we need to pass a current string, the digits input of the problem, and a vector of strings to store the solution.  For this problem, we will also need an index variable to keep track of what digit we're on of digits

    void backtrack(string curr, string dgts, int index, vector<string>& ans) {
        ...
    }

In the main function, we initialize the variables and pass them to the backtracking function.  After the backtracking function returns we return our answer
    
    vector<string> letterCombinations(string digits) {
        ...
        vector<string> answer;
string current="";
int index=0
backtrack(current,digits, index, answer);
return answer;
    }

The beginning of the backtracking function is straightforward.  If our current string reaches the size of the digits input, then we've reached the end of the combinatorial logic and found a solution

if(curr.size()==digits.size()) {
ans.push_back(curr);
return;
}

Now we iterate over the letters for a given point in the program.  We track what index of the digits variable we're finding letters for.  So we first find the digit from the index, then the letters from the digit in the hashmap

string letters = hashmap[digits[index]];

Then like normal backtracking, we add the letter to our solution, backtrack, then remove the letter

    for(int i=0; i<letters.size(); i++) {
curr+=letters[i];
backtrack(curr, digits, index+1, ans);
curr.pop_back();
}

Three days in a row of backtracking

Thanks to the Editorial for approaches to the hashmap

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th