forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0017-letter-combinations-of-a-phone-number.java
55 lines (50 loc) · 1.14 KB
/
0017-letter-combinations-of-a-phone-number.java
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
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
class Solution {
private Map<Character, String> digitToChar = Map.of(
'2',
"abc",
'3',
"def",
'4',
"ghi",
'5',
"jkl",
'6',
"mno",
'7',
"pqrs",
'8',
"tuv",
'9',
"wxyz"
);
public List<String> letterCombinations(String digits) {
if (digits.length() == 0) {
return new ArrayList();
}
List<String> ans = new ArrayList();
String cur = "";
backtrack(digits, ans, cur, 0);
return ans;
}
public void backtrack(
String digits,
List<String> ans,
String cur,
int index
) {
if (cur.length() == digits.length()) {
ans.add(cur);
return;
} else if (index >= digits.length()) {
return;
} else {
String digit = digitToChar.get(digits.charAt(index));
for (char c : digit.toCharArray()) {
backtrack(digits, ans, cur + c, index + 1);
}
}
}
}