知乎ID: 码蹄疾
码蹄疾,毕业于哈尔滨工业大学。
小米广告第三代广告引擎的设计者、开发者;
负责小米应用商店、日历、开屏广告业务线研发;
主导小米广告引擎多个模块重构;
关注推荐、搜索、广告领域相关知识;
题目
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
分析
这实际上就是一个求全排列的问题,求全排列的问题用递归求解,递归求解过程中主要关注退出的条件即可。
Code
class Solution {
public List<String> letterCombinations(String digits) {
String[][] numberList = new String[][]{
{"a", "b", "c"},
{"d", "e", "f"},
{"g", "h", "i"},
{"j", "k", "l"},
{"m", "n", "o"},
{"p", "q", "r", "s"},
{"t", "u", "v"},
{"w", "x", "y", "z"},
};
List<String> res = new ArrayList<>();
if (digits.length() == 0) {
return res;
}
int first = digits.charAt(0) - 48 - 2;
String[] current = numberList[first];
if (digits.length() == 1) {
res.addAll(Arrays.asList(current));
return res;
}
List<String> leftList = letterCombinations(digits.substring(1));
for (String aCurrent : current) {
for (String str : leftList) {
res.add(aCurrent + str);
}
}
return res;
}
}

网友评论