forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLetterCombinationOfPhoneNumber.java
More file actions
39 lines (33 loc) · 1.02 KB
/
LetterCombinationOfPhoneNumber.java
File metadata and controls
39 lines (33 loc) · 1.02 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
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class LetterCombinationOfPhoneNumber {
/**
* leetcode的测试用例中不包括包含"0"或"1"的情况
*/
private static final String[] ARR = {
"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"
};
// 耗时2ms
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
if (digits.length() == 0) {
return res;
}
dfs(digits, new StringBuilder(), res, 0);
return res;
}
private void dfs(String digits, StringBuilder sb, List<String> res, int start) {
if (start >= digits.length()) {
res.add(sb.toString());
return;
}
int n = digits.charAt(start) - '0';
for (char c : ARR[n].toCharArray()) {
sb.append(c);
dfs(digits, sb, res, start + 1);
sb.setLength(sb.length() - 1);
}
}
}