forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
_131.java
67 lines (55 loc) · 1.75 KB
/
_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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
/**
* 131. Palindrome Partitioning
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab",
Return
[
["aa","b"],
["a","a","b"]
]
*/
public class _131 {
public static class Solution1 {
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList();
int n = s.length();
boolean[][] dp = new boolean[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (s.charAt(j) == s.charAt(i) && (j + 1 >= i - 1 || dp[j + 1][i - 1])) {
// j+1 >= i-1 means j and i are adjance to each other or only one char apart from each other
//dp[j+1][i-1] means its inner substring is a palindrome, so as long as s.charAt(j) == s.charAt(i), then dp[j][i] must be a palindrome.
dp[j][i] = true;
}
}
}
for (boolean[] list : dp) {
for (boolean b : list) {
System.out.print(b + ", ");
}
System.out.println();
}
System.out.println();
backtracking(s, 0, dp, new ArrayList(), result);
return result;
}
void backtracking(String s, int start, boolean[][] dp, List<String> temp,
List<List<String>> result) {
if (start == s.length()) {
List<String> newTemp = new ArrayList(temp);
result.add(newTemp);
}
for (int i = start; i < s.length(); i++) {
if (dp[start][i]) {
temp.add(s.substring(start, i + 1));
backtracking(s, i + 1, dp, temp, result);
temp.remove(temp.size() - 1);
}
}
}
}
}