17 Letter Combinations of a Phone Number

1. Question

Given a digit string, 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.
1
Input:
2
Digit string "23"
3
4
Output:
5
["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Copied!
Note: Although the above answer is in lexicographical order, your answer could be in any order you want.

2. Implementation

(1) Backtracking
1
class Solution {
2
public List<String> letterCombinations(String digits) {
3
List<String> res = new ArrayList<>();
4
5
if (digits == null || digits.length() == 0) {
6
return res;
7
}
8
9
String[] keys = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
10
11
StringBuilder combination = new StringBuilder();
12
getLetterCombinations(digits, 0, combination, keys, res);
13
return res;
14
}
15
16
public void getLetterCombinations(String digits, int pos, StringBuilder combination, String[] keys, List<String> res) {
17
if (pos == digits.length()) {
18
res.add(combination.toString());
19
return;
20
}
21
22
String key = keys[digits.charAt(pos) - '0'];
23
for (int i = 0; i < key.length(); i++) {
24
combination.append(key.charAt(i));
25
getLetterCombinations(digits, pos + 1, combination, keys, res);
26
combination.setLength(combination.length() - 1);
27
}
28
}
29
}
Copied!

3. Time & Space Complexity

时间复杂度O(L^n), L为digits的长度, n为一个数字对应的最长letters的长度, 空间复杂度O(L^n)