这道题很明显要用回溯法。和之前我做过的回溯法不一样的点是:每次遍历的字符串是不同的,所以要传进去一个索引,遍历不同的字符串。
class Solution {
List res = new ArrayList<String>();
Map<Character,String> map = new HashMap<>();
public List<String> letterCombinations(String digits) {
if (digits == null || digits.length() == 0) {
return res;
}
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");
dfs(digits,new StringBuilder(),0);
return res;
}
public void dfs(String digits,StringBuilder path,int index){
if(path.length() == digits.length()){
res.add(path.toString());
return;
}
String t = map.get(digits.charAt(index));
for(int i = 0;i < t.length();i++){
path.append(t.charAt(i));
dfs(digits,path,index+1);
path.deleteCharAt(path.length() - 1);
}
}
}