-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLetterCombinations.java
More file actions
39 lines (33 loc) · 1.25 KB
/
Copy pathLetterCombinations.java
File metadata and controls
39 lines (33 loc) · 1.25 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
package LeetcodePractice;
import java.util.ArrayList;
import java.util.List;
public class LetterCombinations {
private static final String[] keyPad = {
"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"
};
public static List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<>();
if (digits == null || digits.length() == 0) {
return result;
}
doBacktracking(result, new StringBuilder(), digits, 0);
return result;
}
private static void doBacktracking(List<String> result, StringBuilder current, String digits, int index) {
if (index == digits.length()) {
result.add(current.toString());
return;
}
String letters = keyPad[digits.charAt(index) - '0'];
for (char letter : letters.toCharArray()) {
current.append(letter);
doBacktracking(result, current, digits, index + 1);
current.deleteCharAt(current.length() - 1);
}
}
public static void main(String[] args) {
System.out.println(letterCombinations("23"));
System.out.println(letterCombinations(""));
System.out.println(letterCombinations("2"));
}
}