public class _17电话号码的字母组合_hot {
public List<String> letterCombinations(String digits) {
List<String> combinations = new ArrayList<>();
if (digits.isEmpty()) {
return combinations;
}
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");
}};
backtrack(combinations, phoneMap, digits, 0, "");
return combinations;
}
public void backtrack(List<String> combinations,
Map<Character, String> phoneMap,
String digits, // 输入的参数
int index, // 递归level
String combination) { //最后生成的参数
// todo 1、terminator 满足结束条件
if (index == digits.length()) {
combinations.add(combination);
return;
}
// todo 2、process 在选择列表里面做选择,backtrack之前做选择,backtrack撤销选择
// 数字
char digit = digits.charAt(index);
// 字母
String letters = phoneMap.get(digit);
for (int i = 0; i < letters.length(); i++) {
// todo 3、drill down,进入下一层
backtrack(combinations, phoneMap, digits, index + 1, combination);
}
}
回溯算法:电话号码的字母组合
于 2024-07-31 14:16:12 首次发布