答案:
class Solution {
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<String>();
if(digits.length()==0){
return res;
}
Map<Character, String> phoneMap = new HashMap<Character, String>() {{
put('2', "abc");
put('3', "def");
put('4', "ghi");
put('5', "jkl");
put('6', "mno");
put('7', "pqrs");
put('8', "tuv");
put('9', "wxyz");
}};
findNext(res, phoneMap, digits, 0, new StringBuffer());
return res;
}
private void findNext(List<String> res, Map<Character,String> phoneMap, String digits, int index, StringBuffer str){
if(index >= digits.length()){
res.add(str.toString());
}else{
char digit = digits.charAt(index);
String letters = phoneMap.get(digit);
for(int i=0;i<letters.length();i++){
str.append(letters.charAt(i));
findNext(res,phoneMap,digits,index+1,str);
str.deleteCharAt(index);
}
}
}
}
补: 这个叫回溯法 新学的