给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
分析
- 回溯
解法
-
得到完整的字母排列后,进行回退,遍历其余字母排列
-
时间复杂度O(\(3^m*4^n\)),m、n分别为对应3个、4个字母的数字个数
-
空间复杂度O(\(m+n\))
class Solution {
public List<String> letterCombinations(String digits) {
ArrayList<String> combinations = new ArrayList<>();
// 输入为空的情况
if(digits.length() == 0) return combinations;
HashMap<Character, String> phoneMap = new HashMap<Character, String>() {};
phoneMap.put(\'2\', "abc");
phoneMap.put(\'3\', "def");
phoneMap.put(\'4\', "ghi");
phoneMap.put(\'5\', "jkl");
phoneMap.put(\'6\', "mno");
phoneMap.put(\'7\', "pqrs");
phoneMap.put(\'8\', "tuv");
phoneMap.put(\'9\', "wxyz");
backtrack(combinations, phoneMap, digits, 0, new StringBuffer());
return combinations;
}
public void backtrack(ArrayList<String> combinations, HashMap<Character, String> phoneMap, String digits, int index, StringBuffer combination){
// 得到完整的字母排列后,进行回退
if(index == digits.length()){
combinations.add(combination.toString());
}else {
char digit = digits.charAt(index);
String letters = phoneMap.get(digit);
// 遍历该数字对应的每个字母
for(int i = 0; i < letters.length(); i++){
combination.append(letters.charAt(i));
backtrack(combinations, phoneMap, digits, index+1, combination);
combination.deleteCharAt(index);
}
}
}
}
//class Test{
// public static void main(String[] args) {
// Solution test = new Solution();
// String digits = "234";
// System.out.println(test.letterCombinations(digits));
// }
//}