Leetcode 17. Letter Combinations of a Phone Number
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.
2 -> "abc"
3 -> "def"
4 -> "ghi"
5 -> "jkl"
6 -> "mno"
7 -> "pqrs"
8 -> "tuv"
9 -> "wxyz"
The input is a string that contains digits ranging from 2 to 9. You need to return all possible letter combinations you can get by pressing these started next number of buttons.
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
Although the above answer is in lexicographical order, your answer could be in any order you want.
import java.util.ArrayList;
import java.util.List;
public class Solution {
private static final String[] KEYPAD = {
"", // 0
"", // 1
"abc", // 2
"def", // 3
"ghi", // 4
"jkl", // 5
"mno", // 6
"pqrs", // 7
"tuv", // 8
"wxyz" // 9
};
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<>();
if (digits == null || digits.length() == 0) {
return result;
}
backtrack(result, new StringBuilder(), digits, 0);
return result;
}
private void backtrack(List<String> result, StringBuilder current, String digits, int index) {
if (index == digits.length()) {
result.add(current.toString());
return;
}
String letters = KEYPAD[digits.charAt(index) - '0'];
for (char letter : letters.toCharArray()) {
current.append(letter);
backtrack(result, current, digits, index + 1);
current.deleteCharAt(current.length() - 1); // backtrack
}
}
public static void main(String[] args) {
Solution solution = new Solution();
String digits = "23";
List<String> combinations = solution.letterCombinations(digits);
for (String combination : combinations) {
System.out.println(combination);
}
}
}
The time complexity of this solution is O(3^N * 4^M), where N is the number of digits corresponding to 3 letters (2-6, 8) and M is the number of digits corresponding to 4 letters (7, 9).
The recursive backtracking approach explores all possible combinations formed by these letters.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?