【每日一题-leetcode】17.电话号码的字母组合
17.电话号码的字母组合
- 电话号码的字母组合
难度中等688
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:"23" 输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
回溯
ArrayList<String> result = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if(digits == null ||digits.length() == 0){
return result;
}
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'});
conbin(digits,0,new StringBuilder().append(""),map);
return result;
}
public void conbin(String digits, int depth, StringBuilder str,HashMap<Character,char[]> map){
if(depth == digits.length()){
result.add(str.toString());
return ;
}
//选择列表
char temp = digits.charAt(depth);
char[] charArr = map.get(temp);
for(int i = 0; i<charArr.length; i++){
//做出选择
str.append(charArr[i]);
conbin(digits,depth+1,str,map);
//撤销选择
str.deleteCharAt(str.length() - 1);
}
}