问题描述:给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:digits = "23" 输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
解题思路:
我想的是按照树的dfs做,不知道怎么动手
打开评论区,先做出来再理解吧。
本题是一个电话号码组合的问题,或者说是一个全排列问题。
路径:也就是已经做出的选择。
选择列表:也就是你当前可以做的选择。
结束条件:也就是到达决策树底层,无法再做选择的条件。
我们所使用的框架基本就是:
其中最关键的点就是:在递归之前做选择,在递归之后撤销选择。
实现代码:
class Solution {
List<String> list = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if(digits.length()==0||digits==null)
return list;
HashMap<Character,char[]> map = new HashMap<>();
map.put('2',new char[]{'a','b','c'});
map.put('3',new char[]{'d','e','f'});
map.put('4',new char[]{'g','h','i'});
map.put('5',new char[]{'j','k','l'});
map.put('6',new char[]{'m','n','o'});
map.put('7',new char[]{'p','q','r','s'});
map.put('8',new char[]{'t','u','v'});
map.put('9',new char[]{'w','x','y','z'});
combin(digits,0,new StringBuilder().append(""),map);
return list;
}
private void combin(String digits, int depth, StringBuilder str, Map<Character,char[]> map){
if(depth==digits.length()){
list.add(str.toString());
return;
}
char temp = digits.charAt(depth);
char[] charArr = map.get(temp);
for(char c : charArr){
str.append(c);
combin(digits,depth+1,str,map);
str.deleteCharAt(depth);
}
}
}