题目:电话号码的字母组合
描述:给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。数字到字母的映射与电话按键相同。注意 1 不对应任何字母。
示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
解法一:模拟进制
class Solution {
public List<String> letterCombinations(String digits) {
if ("".equals(digits)) {
return Collections.emptyList();
}
String[] strings = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
List<String> list = new ArrayList<>();
int size = digits.length();
// 表示各个位 当前字母索引
int[] loop = new int[size];
// 最高位字符串长度
int length = strings[digits.charAt(0)-'0'].length();
while (loop[0] != length) {
char[] tempChar = new char[size];
for (int i = 0; i < loop.length; i++) {
// 按 loop 中索引取出各个位字符
tempChar[i] = strings[digits.charAt(i)-'0'].charAt(loop[i]);
}
list.add(String.valueOf(tempChar));
// 最右索引 + 1, 如果索引越界, 向前进位
loop[size - 1] += 1;
for (int i = loop.length - 1; i > 0; i--) {
if (loop[i] == strings[digits.charAt(i)-'0'].length()) {
loop[i - 1] = loop[i - 1] + 1;
loop[i] = 0;
}
}
}
return list;
}
}
- 时间复杂度:
其中 N 是输入数字中对应 3 个字母的数目(比方说 2,3,4,5,6,8), M 是输入数字中对应 4 个字母的数目(比方说 7,9),N+M 是输入数字的总数。
- 空间复杂度:
要存储
个结果
解法二:回溯
class Solution {
Map<String, String> phone = new HashMap<String, String>() {{
put("2", "abc");
put("3", "def");
put("4", "ghi");
put("5", "jkl");
put("6", "mno");
put("7", "pqrs");
put("8", "tuv");
put("9", "wxyz");
}};
List<String> output = new ArrayList<String>();
public void backtrack(String combination, String next_digits) {
// if there is no more digits to check
if (next_digits.length() == 0) {
// the combination is done
output.add(combination);
}
// if there are still digits to check
else {
// iterate over all letters which map
// the next available digit
String digit = next_digits.substring(0, 1);
String letters = phone.get(digit);
for (int i = 0; i < letters.length(); i++) {
String letter = phone.get(digit).substring(i, i + 1);
// append the current letter to the combination
// and proceed to the next digits
backtrack(combination + letter, next_digits.substring(1));
}
}
}
public List<String> letterCombinations(String digits) {
if (digits.length() != 0)
backtrack("", digits);
return output;
}
}
- 时间复杂度:
其中 N 是输入数字中对应 3 个字母的数目(比方说 2,3,4,5,6,8), M 是输入数字中对应 4 个字母的数目(比方说 7,9),N+M 是输入数字的总数。
- 空间复杂度:
要存储
个结果