题目链接
思路:
采用回溯搜索算法。
对于给定的数字字符串digits,每一位数字所对应的字母都需要进行组合。即 需要穷举所有的可能 来找到符合题目条件的解。
此题需要注意边界条件:当所选择出的组合已经满足题目要求时,需要将其加入解中。
在每一次回溯之后,都需要删除掉当前的选择。
这种题目做多了就会有感觉了,刚开始,确实很难做出来。
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);
}
}