-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
42 lines (39 loc) · 1.21 KB
/
Copy pathsolution.java
File metadata and controls
42 lines (39 loc) · 1.21 KB
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
33
34
35
36
37
38
39
40
41
42
import java.util.*;
class Solution {
private static final String[] DIGIT_TO_CHARS = {
"", // 0
"", // 1
"abc", // 2
"def", // 3
"ghi", // 4
"jkl", // 5
"mno", // 6
"pqrs",// 7
"tuv", // 8
"wxyz" // 9
};
public ArrayList<String> possibleWords(int[] arr) {
ArrayList<String> res = new ArrayList<>();
if (arr == null || arr.length == 0) return res;
backtrack(arr, 0, new StringBuilder(), res);
return res;
}
private void backtrack(int[] arr, int idx, StringBuilder cur, ArrayList<String> res) {
if (idx == arr.length) {
if (cur.length() > 0) res.add(cur.toString());
return;
}
int d = arr[idx];
if (d < 0 || d > 9) return;
String letters = DIGIT_TO_CHARS[d];
if (letters.isEmpty()) {
backtrack(arr, idx + 1, cur, res); // skip 0 and 1
return;
}
for (int i = 0; i < letters.length(); i++) {
cur.append(letters.charAt(i));
backtrack(arr, idx + 1, cur, res);
cur.deleteCharAt(cur.length() - 1);
}
}
}