[Link] https://leetcode.com/problems/letter-combinations-of-a-phone-number/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
int len;
public List<String> letterCombinations(String digits) {
if(digits.length() == 0) return new ArrayList<String>();
ArrayList<String> answer = new ArrayList<String>();
ArrayList<ArrayList<Character>> dialNum = new ArrayList<> ();
StringBuilder sb = new StringBuilder();
int curIdx = 0, number;
for(int i = 2; i < 10; i++) {
if(i == 7 || i == 9) number = 4;
else number = 3;
ArrayList<Character> temp = new ArrayList<>();
for(int j = 0; j < number; j++) temp.add((char)('a'+ curIdx++));
dialNum.add(temp);
}
len = dialNum.size();
dfs(digits, 0, dialNum, sb, answer);
return answer;
}
void dfs(String digits, int index, ArrayList<ArrayList<Character>> dialNum, StringBuilder sb, ArrayList<String> answer) {
if(index == digits.length()) {
answer.add(sb.toString());
return;
}
for(char c: dialNum.get(digits.charAt(index) - '2')) {
sb.append(c);
dfs(digits, index + 1, dialNum, sb, answer);
sb.setLength(Math.max(0, sb.length() - 1));
}
}
}