-
Notifications
You must be signed in to change notification settings - Fork 0
/
PalindromePartitioning.java
39 lines (34 loc) · 1.01 KB
/
PalindromePartitioning.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
// https://leetcode.com/problems/palindrome-partitioning/
// #dynamic-programming #backtracking #dfs
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<List<String>>();
ArrayList<String> curList = new ArrayList<>();
backtracking(0, result, curList, s);
return result;
}
private void backtracking(int start, List<List<String>> result, List<String> curList, String s) {
if (start >= s.length()) {
result.add(new ArrayList<>(curList));
}
for (int i = start; i < s.length(); i++) {
if (isPalindrome(start, i, s)) {
// forward
curList.add(s.substring(start, i + 1));
backtracking(i + 1, result, curList, s);
// backward
curList.remove(curList.size() - 1);
}
}
}
private boolean isPalindrome(int start, int end, String s) {
while (start < end) {
if (s.charAt(start) != s.charAt(end)) {
return false;
}
start++;
end--;
}
return true;
}
}