方法:回溯
class Solution {
//数字到字母的映射
String[] map = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
//结果集
List<String> ans = new ArrayList<>();
//临时路径
StringBuilder sb = new StringBuilder();
public List<String> letterCombinations(String digits) {
if (digits == null || digits.length() == 0) return ans;
backtracking(digits, 0);
return ans;
}
public void backtracking(String digits, int index) {
//收集结果
if (sb.length() == digits.length()) {
ans.add(sb.toString());
return;
}
//得到数字对应的字母
String chs = map[digits.charAt(index) - '2'];
for (char ch : chs.toCharArray()) {
sb.append(ch);
//向下一个数字递归
backtracking(digits, index + 1);
//撤销上一次的选择
sb.deleteCharAt(sb.length() - 1);
}
}
}