这个挺容易想明白的,就是写代码的时候,用回溯法,涉及到递归调用的时候有点绕
代码:
public class LetterCombinations {
public static void main(String[] args) {
System.out.println(letterCombinations("234"));
}
public static List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<>();
Map<Integer, String> hashMap = new HashMap<>();
hashMap.put(2, "abc");
hashMap.put(3, "def");
hashMap.put(4, "ghi");
hashMap.put(5, "jkl");
hashMap.put(6, "mno");
hashMap.put(7, "pqrs");
hashMap.put(8, "tuv");
hashMap.put(9, "wxyz");
if (digits.length() > 0) {
backTrace(hashMap, 0, digits, list, new StringBuffer());
}
return list;
}
private static void backTrace(Map<Integer, String> hashMap, int index, String digits, List<String> list, StringBuffer stringBuffer) {
if (digits.length() == index) {
list.add(stringBuffer.toString());
} else {
String temp = hashMap.get(digits.charAt(index) - 48); //获取数字对应的字符串
for (int i = 0; i < temp.length(); i++) {
stringBuffer.append(temp.charAt(i));
backTrace(hashMap,index+1,digits,list,stringBuffer);
stringBuffer.deleteCharAt(index); //这句不容易想到
}
}
}
}