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.
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
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
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
Then like normal backtracking, we add the letter to our solution, backtrack, then remove the letter
Three days in a row of backtracking
Thanks to the Editorial for approaches to the hashmap
Comments
Post a Comment