Given a string digits containing 2 to 9 inclusive, return in sorted lexicographic order all possible strings it could represent when mapping to letters on a phone dialpad.
These are the mappings on a phone dialpad:
| 2 | abc | | 3 | def | | 4 | ghi | | 5 | jkl | | 6 | mno | | 7 | pqrs | | 8 | tuv | | 9 | wxyz |Example 1
Input
digits = “23”
Output["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
Phone Number Permutation using Depth First Search Algorithm
We can try building the permutation digit by digit. We store the mapping in a dictionary, then look it up while during Depth First Search. We can spawn out the search tree digits by digits until we have built the size-n permutation where n is the length of the digits.
class Solution:
def phoneNumberPermutation(self, digits):
m = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz"
}
ans = []
def dfs(cur):
if len(cur) == len(digits):
ans.append(cur)
return
for n in m[digits[len(cur)]]:
dfs(cur + n)
dfs("")
return ans
The complexity is roughly O(3^N) if each digit has 3 possibilities. The space complexity is O(N) where N is the number of digits in the original string (and because we are using Recursion).
–EOF (The Ultimate Computing & Technology Blog) —
270 wordsLast Post: Teaching Kids Programming - Recursive Algorithm to Invert a Binary Tree
Next Post: Teaching Kids Programming - Recursive Algorithm to Determine if a Binary Tree is Symmetric