-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path17.java
60 lines (54 loc) · 1.58 KB
/
17.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
56
57
58
59
60
class Solution {
private static final String[] MAPPING = new String[] { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv",
"wxyz" };
private final List<String> ans = new ArrayList<>();
private char[] digits, path;
public List<String> letterCombinations(String digits) {
int n = digits.length();
if(n==0)
return List.of();
this.digits = digits.toCharArray();
path = new char[n];
dfs(0);
return ans;
}
private void dfs(int i){
if(i==digits.length){
ans.add(new String(path));
return ;
}
for(char c: MAPPING[digits[i]-'0'].toCharArray()){
path[i]=c;
dfs(i+1);
}
}
}
// 第二次做法:统一回溯的写法
class Solution {
private static final String[] MAPPING = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
private List<String> ans = new ArrayList<>();
private char[] path;
private char[] nums;
public List<String> letterCombinations(String digits) {
this.nums = digits.toCharArray();
int n = nums.length;
if(n==0){
return List.of();
}
path = new char[n];
dfs(0);
return ans;
}
private void dfs(int length){
if(length == nums.length){
ans.add(new String(path));
return;
}
for(char c :MAPPING[nums[length]-'0'].toCharArray()){
path[length] = c;
length++;
dfs(length);
length--;
}
}
}