【DFS】LeetCode 17. 电话号码的字母组合
题目链接
思路
使用 DFS
进行枚举。
代码
class Solution {
private HashMap<Character, char[]> map = new HashMap<>();
private List<String> result = new ArrayList<>();
private char[] s;
public List<String> letterCombinations(String digits) {
if(digits.equals("")){
return new ArrayList();
}
init();
s = digits.toCharArray();
int len = s.length;
dfs(0, len, new StringBuilder());
return result;
}
private void dfs(int index, int len, StringBuilder stringBuilder) {
if(index == len){
result.add(stringBuilder.toString());
return;
}
System.out.println("index = " + index);
char[] temp = map.get(s[index]);
for(char c : temp){
stringBuilder.append(c);
dfs(index + 1, len, stringBuilder);
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
}
}
void init(){
map.put('2', new char[]{'a', 'b', 'c'});
map.put('3', new char[]{'d', 'e', 'f'});
map.put('4', new char[]{'g', 'h', 'i'});
map.put('5', new char[]{'j', 'k', 'l'});
map.put('6', new char[]{'m', 'n', 'o'});
map.put('7', new char[]{'p', 'q', 'r', 's'});
map.put('8', new char[]{'t', 'u', 'v'});
map.put('9', new char[]{'w', 'x', 'y', 'z'});
}
}