public class Solution {
static Map<Character,String> map = new HashMap<>();
static List<String> list = null;
static {
map.put('2', "abc");
map.put('3', "def");
map.put('4', "ghi");
map.put('5', "jkl");
map.put('6', "mno");
map.put('7', "pqrs");
map.put('8', "tuv");
map.put('9', "wxyz");
}
public List<String> letterCombinations(String digits) {
list= new ArrayList<>();
if (digits.length()==0) return list;//剪掉特殊情况 否则返回一个StringBuilder创建的空串
dfs(0,digits,new StringBuilder());
return list;
}
private void dfs(int step,String digits,StringBuilder sb){
if (step==digits.length()-1){//添加结果集
list.add(sb.toString());
}else {
char digit = digits.charAt(step);
String strmap = map.get(digit);
for (int i = 0; i < strmap.length(); i++) {
sb.append(strmap.charAt(i));
dfs(step+1,digits,sb);
sb.deleteCharAt(step);//回溯 删掉当前位置字符
}
}
}
}
LeetCode17(dfs)
最新推荐文章于 2022-05-16 00:13:11 发布