Problem
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example:
1 |
|
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
Explanation
-
We can use DFS to solve this problem.
-
If the input is
"23"
, then we can draw the following tree:
1 |
|
-
When using DFS, we need to think of the base case. The base case is when the
level
reaching the end, in this case when we reaches level 2, we already gotad
, then we need to append it to the result and return. -
In this case, we will get
ad
, append to theres
, then remove thed
; we then getae
, append to theres
, then remove thee
; we then getaf
, append to theres
, then remove thef
. Now we finish looping level1, we return back to level 0. Then remove thea
, looping to the next charb
and repeat.
Solution
1 |
|