给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
示例 1: 输入:digits = "23" 输出:["ad","ae","af","bd","be","bf","cd","ce","cf"] 示例 2: 输入:digits = "" 输出:[] 示例 3: 输入:digits = "2" 输出:["a","b","c"]
代码语言:javascript复制class Solution {
String [] map={"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
StringBuilder sb=new StringBuilder();
List<String> res=new ArrayList();
public List<String> letterCombinations(String digits) {
if(digits==null||digits.length()==0) return res ;
backDfs(digits,0);//dfs
return res;
}
public void backDfs(String digits,int index){//数字 ,当前第几个数字了
if(index==digits.length()){
//吧字符串添加到当前结果集
res.add(sb.toString());
return ;
}
String val=map[digits.charAt(index)-'2'];
for(char c:val.toCharArray()){
sb.append(c);//当前数字对应的字母 要一个
backDfs(digits,index 1);//继续确定第二个数字要那个字母
//回溯
sb.deleteCharAt(sb.length()-1);
}
}
}