class Solution {标签:index,17,组合,res,phoneMap,str,电话号码,put,sb From: https://www.cnblogs.com/MarkLeeBYR/p/18007531
private final Map<Character, String> phoneMap = new HashMap<Character, String>();
public void init() {
phoneMap.put('2', "abc");
phoneMap.put('3', "def");
phoneMap.put('4', "ghi");
phoneMap.put('5', "jkl");
phoneMap.put('6', "mno");
phoneMap.put('7', "pqrs");
phoneMap.put('8', "tuv");
phoneMap.put('9', "wxyz");
}
public List<String> letterCombinations(String str) {
List<String> res = new ArrayList<String>();
if (str.length() == 0) {
return res;
}
init();
backtrack(res, phoneMap, str, 0, new StringBuffer());
return res;
}
public void backtrack(List<String> res, Map<Character, String> phoneMap, String str, int index, StringBuffer sb) {
if (index == str.length()) {
res.add(sb.toString());
return;
}
String letters = phoneMap.get(str.charAt(index));
int lettersCount = letters.length();
for (int i = 0; i < lettersCount; i++) {
sb.append(letters.charAt(i));
backtrack(res, phoneMap, str, index + 1, sb);
sb.deleteCharAt(index);
}
}
}