Backtracking
Medium
Given a string containing digits from2-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:
Copy Input:
"23"
Output:
["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
Analysis
The phone digits to letters mapping:
Copy String [] KEYS = { "" , "" , "abc" , "def" , "ghi" , "jkl" , "mno" , "pqrs" , "tuv" , "wxyz" }
Solution
Recursive
利用递归,每次递归选择当前数字对应字符,然后将index+1,用下一个数字进入下一层递归;递归返回的条件是String path达到digits的长度,代表了一个组合的生成结束了,放入结果中即可。
Time complexity : O(3^N × 4^M ) where N is the number of digits in the input that maps to 3 letters (e.g. 2, 3, 4, 5, 6, 8) and M is the number of digits in the input that maps to 4 letters (e.g. 7, 9), and N+M is the total number digits in the input.
Space complexity : O(3^N × 4^M ) since one has to keep 3^N times 4^M solutions.
https://leetcode.com/problems/letter-combinations-of-a-phone-number/solution/
Copy class Solution {
private static final String [] KEYS = { "" , "" , "abc" , "def" , "ghi" , "jkl" , "mno" , "pqrs" , "tuv" , "wxyz" };
public List < String > letterCombinations ( String digits) {
List < String > res = new ArrayList <>();
if ( digits . length () == 0 ) {
return res;
}
helper(digits , 0 , "" , res) ;
return res;
}
private void helper ( String digits , int index , String path , List < String > res) {
if (index == digits . length ()) {
res . add ( path . toString ());
return ;
}
String letters = KEYS [ digits . charAt (index) - '0' ];
for ( char c : letters . toCharArray ()) {
helper(digits , index + 1 , path + c , res) ;
}
}
}
Queue, BFS
Copy class Solution {
public List < String > letterCombinations ( String digits) {
LinkedList < String > queue = new LinkedList() ;
if (digits == null || digits . length () == 0 ) {
return queue;
}
char [] digitChar = digits . toCharArray ();
String [] phone = new String [] { "" , "" , "abc" , "def" , "ghi" , "jkl" , "mno" , "pqrs" , "tuv" , "wxyz" };
queue . offer ( "" );
for ( int i = 0 ; i < digitChar . length ; i ++ ) {
char [] letters = phone[digitChar[i] - '0' ] . toCharArray ();
while ( queue . peek () . length () == i) {
String str = queue . poll ();
for ( char c : letters) {
queue . offer (str + c);
}
}
}
return queue;
}
}
https://leetcode.com/problems/letter-combinations-of-a-phone-number/discuss/?currentPage=1&orderBy=most_votes&query=