Nameless Site

But one day, you will stand before its decrepit gate,without really knowing why.

0%

电话号码的字母组合

来源Leetcode第17题电话号码字母组合

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例:

输入:”23”
输出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

想了一下还是逐个数字生成组合,人后根据生成的组合再组合生成对应的代码但是这样的代码量有点问题,现在明明也做了些题,但是代码、算法意识什么的基本还是没有,唉。

官方题解的描述是一个树,通过回溯穷举所有可能情况来找到所有解的算法,如果一个候选解最后被发现并不是可行解,回溯算法会舍弃它,并在前面的一些步骤做出一些修改,并重新尝试找到可行解。
给出如下回溯函数 backtrack(combination, next_digits) ,它将一个目前已经产生的组合 combination 和接下来准备要输入的数字 next_digits 作为参数。
如果没有更多的数字需要被输入,那意味着当前的组合已经产生好了。
如果还有数字需要被输入:
遍历下一个数字所对应的所有映射的字母。
将当前的字母添加到组合最后,也就是 combination = combination + letter 。
重复这个过程,输入剩下的数字: backtrack(combination + letter, next_digits[1:]) 。

代码如下:

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
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");
}}; //生成哈希图,对应着8个数字按键与字母的组合

List<String> output = new ArrayList<String>();//返回的List 包含若干个组合字符串

public void backtrack(String combination, String next_digits) {
// 如果没有数字需要继续匹配组合了
if (next_digits.length() == 0) {
output.add(combination);
}
// 还有数字要生成对应的字母组合
else {
// 循环遍历地图里当前字母所对应的字符串里的所有字母
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);
// 将当前字母加入组合,并且将数字串减1开始下一层的回溯
backtrack(combination + letter, next_digits.substring(1));
}
}
}

public List<String> letterCombinations(String digits) {
if (digits.length() != 0)
backtrack("", digits);
return output;
}
}