给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例 1:
输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2:
输入:digits = "2"
输出:["a","b","c"]
提示:
1 <= digits.length <= 4
digits[i] 是范围 ['2', '9'] 的一个数字。
思路 :考虑两点。第一点,当前数字考虑后是否还会被考虑?第二点,遍历的位置?第一点,当前数字对应字母情况考虑后,不会再被考虑。第二点,每次考虑当前数字即可。
综上,dfs中使用index考虑当前数字的情况,下一个数字的情况用index+1考虑。
代码:
c
class Solution {
Map<Integer,String> phoneKey = new HashMap<>();
public List<String> letterCombinations(String digits) {
phoneKey.put(2,"abc");
phoneKey.put(3,"def");
phoneKey.put(4,"ghi");
phoneKey.put(5,"jkl");
phoneKey.put(6,"mno");
phoneKey.put(7,"pqrs");
phoneKey.put(8,"tuv");
phoneKey.put(9,"wxyz");
List<String> res = new ArrayList<>();
dfs(digits, 0, "", res);
return res;
}
public void dfs(String digits, int index, String temp, List<String> res){
if(index==digits.length()){
res.add(temp);
return;
}
// 当前数字可以表示的字母情况
String s = phoneKey.getOrDefault(Integer.parseInt(String.valueOf(digits.charAt(index))),"");
for(int i = 0;i<s.length();i++){
dfs(digits, index+1,temp+s.charAt(i),res);
}
}
}