-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLC_131.java
43 lines (38 loc) · 1.16 KB
/
LC_131.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
import java.util.ArrayList;
import java.util.List;
public class LC_131 {
static List<List<String>> res = new ArrayList<>();
static List<String> path = new ArrayList<>();
public static List<List<String>> partition(String s) {
backtrack(s, 0);
return res;
}
public static void backtrack(String s, int startIdx) {
if (startIdx == s.length()) {
res.add(new ArrayList<>(path));
return;
}
for (int i = startIdx; i < s.length(); i++) {
if (!isValid(s.substring(startIdx, i + 1))) continue;
path.add(s.substring(startIdx, i + 1));
System.out.println("前 path:" + path);
backtrack(s, i + 1);
path.remove(path.size() - 1);
System.out.println("后 path:" + path);
}
}
public static boolean isValid(String s) {
int l = 0;
int r = s.length() - 1;
while (l <= r) {
if (s.charAt(l) != s.charAt(r)) return false;
l++;
r--;
}
return true;
}
public static void main(String[] args) {
String s = "aab";
partition(s);
}
}