[LeetCode] Top Interview 150 Problems Solving # 17 Letter Combinations of a Phone Number
Understanding the Problem
Each dial of the telephone has 3-4 letters on them. It is to have all the possible combination of the dials. For instance, if the dial hits 2
, which has letters “abc”
, and 3
, which has letters “def”
, the combination will be [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”]
.
The length of the dials could be equal or less than 4.
Approach
It is a recursion problem. Simple as that, but did I know it from the beginning? No, I was again fooled by the multiple iterations and was trying to solve it with the snapshot idea that I had earlier. My snapshot idea would work though, but it will only give me a pain even though I get to solve it, like a victory for nothing.
First, I need a dial dictionary to transform the numbers into letters in the middle of the codes. Then I need to think about how the recursion should work. The idea of slicing and giving the digits[1:]
value to the next self function would work, I thought.
Solution
dials = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz"
}
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if len(digits) == 0: # exceptions
return []
elif len(digits) == 1:
return [i for i in dials[digits]]
combination = []
for i in dials[digits[0]]:
for j in self.letterCombinations(digits[1:]):
combination.append(i+j)
return combination
So, the final code was more simple than I thought. It is important to ascertain the returning codes before running the entire codes. These are the steps I followed to solve the problem.
Get dials dictionary
Write codes for the exceptions for when the length of the digits are either
0
or1
If the length of the digits is longer than 1, the slice technique will be applied to cut it into smaller list.
dials[digits[0]]
should be the firstfor
loop to be able to elucidate the operation of the combination with the next slices.
When it is time to go through for j in self.letterCombinations(digits[1:]):
, the returned list from elif len(digits) == 1:
will be used to have combination.
Reflection
Well, while I was writing the codes down, I found out that I had a elif
condition which was useless in the codes but it ran just fine not affecting any runtime ms, but I took it out anyways to make it look much more simple.
It seems that the recursion problem practice somehow augmented my confidence in solving this kind of a problem, that I need to pick up the right spot with the right return codes to make it work like magic.