题目描述
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:”23″
输出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
思路分析
教科书般的DFS实现
就是abc然后分别对接def,深度优先搜索,每条路径优先走到最深,ad,ae…自然就出来了
DFS的模板伪代码如下
dfs(information, pos, temp, result){
if(深度足够了){
result.add(temp);
return;
}
for(;;;) {
update_temp;
dfs(information, pos + 1, new_temp, result);
}
}
代码实现
class Solution {
static Map<Character,String> letterDict = new HashMap();
static {
letterDict.put('2', "abc");
letterDict.put('3', "def");
letterDict.put('4', "ghi");
letterDict.put('5', "jkl");
letterDict.put('6', "mno");
letterDict.put('7', "pqrs");
letterDict.put('8', "tuv");
letterDict.put('9', "wxyz");
}
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList();
if(digits == null || digits.length() == 0) {
return result;
}
String temp = "";
dfs(digits, 0, temp, result);
return result;
}
private void dfs(String digits, int i, String temp, List<String> result) {
if(i >= digits.length()) {
result.add(temp);
return;
}
char num = digits.charAt(i);
String alphas = letterDict.get(num);
for(int j = 0; j < alphas.length(); j++) {
char c = alphas.charAt(j);
dfs(digits, i + 1, temp + c, result); // 考虑复用,以节省temp的空间
}
}
}
总结
记住DFS的套路,
DFS = 循环里面套递归
DFS方法本身的特性就是,
- 返回值是void,靠一个外面传进来的result作为返回
- 有条件传的需要对其DFS的东西information
- 有当前遍历的位置position
- 有一个中间变量temp来记录每次DFS探索到最深之后记录的中间值temp
发表回复