首先用哈希表将数字与对应的字母映射起来,然后进行回溯操作。
回溯可找到所有的可行解,如果发现一个解不可行,则舍弃。每个数字对应的字母都可能进入字母组合,所以直接穷举所有的解即可。
回溯过程中维护一个combination字符串,表示已有的字符排列,初始为空,每次取电话号码的一位数字,从哈希表中获得该数字对应的所有字母,将其中一个字母插入到combination后,然后继续处理电话号码的后一位数字,直到处理完所有的digit,即得到一个完整的字母排列,然后进行回退操作,遍历其余的字母排列。代码如下:
class Sloution{
public List<String> letterCombinations(String digits){
List<String> combinations = new ArrayList<String>();
if(digits.length() == 0){
return combinations;
}
Map<Character, String> phoneMap = new HashMap<Character, 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");
}};
backtrack(combinations, phoneMap, digits, 0, new StringBuffer());
return combinations;
}
public void backtrack(List<String> combinations, Map<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, conbination);
combination.deleteCharAt(index);
}
}
}
}
时间复杂度:O(3^ m ×4^ n),其中 m 是输入中对应 3 个字母的数字个数(包括数字 2、3、4、5、6、8),n 是输入中对应 4 个字母的数字个数(包括数字 7、9),m+n 是输入数字的总个数。当输入包含 m 个对应 3 个字母的数字和 n 个对应 4 个字母的数字时,不同的字母组合一共有 3^ m ×4^ n 种,需要遍历每一种字母组合。
空间复杂度:O(m+n),其中 m 是输入中对应 3 个字母的数字个数,n 是输入中对应 4 个字母的数字个数,m+n 是输入数字的总个数。除了返回值以外,空间复杂度主要取决于哈希表以及回溯过程中的递归调用层数,哈希表的大小与输入无关,可以看成常数,递归调用层数最大为 m+n。