电话号码的字母组合

问题陈述

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例:

1
2
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution{
public List<String> letterCombinations(String digits){
List<String> list=new ArrayList<>();
if(digits==null||digits.length()==0){
return list;
}
Map<Character,String> map=new HashMap<>();
map.put('2', "abc");
map.put('3', "def");
map.put('4', "ghi");
map.put('5', "jkl");
map.put('6', "mno");
map.put('7', "pqrs");
map.put('8', "tuv");
map.put('9', "wxyz");
backTrack(list, digits, map, 0, new StringBuilder());
return list;
}
public void backTrack(List<String> list,String digits,Map<Character,String> map,int index,StringBuilder sb){
// recursion teminator
if (sb.length() == digits.length()) {
list.add(sb.toString());
return;
}

// process current logic
String value = map.get(digits.charAt(index));
for (int j = 0; j < value.length(); j++) {

// drill down
backTrack(list, digits, map, index + 1, sb.append(value.charAt(j)));

// reverse states
sb.deleteCharAt(sb.length() - 1);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution{
public List<String> letterCombinations(String digits){
if(digits==null||digits.length()==0) return new ArrayList<String>();
String[] letter_Map={" ","*","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
List<String> res=new ArrayList<>();
res.add("");
for(int i=0;i<digits.length();i++){//length用作函数调用时加括号
String letters=letter_Map[digits.charAt(i)-'0'];//某字符减去0字符等于该字符对应的数字。
int size=res.size();
for(int j=0;j<size;j++){
String temp=res.remove(0);
for(int k=0;k<letters.length();k++){
res.add(temp+letters.charAt(k));
}
}
}
}
}

另解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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++) {//letters表示该数字在phone中对应的字符串
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;
}
}