Given a string s, partition s such that every substring of the partition is a palindrome.

Return the minimum cuts needed for a palindrome partitioning of s.

1
2
3
Input: "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.

实际上类似Combination III -> Combination IV: 从dfs变为dp; 问法也从比较严格的需要返回所有结果的dfs变为返回比较松散只需要返回数量的dp; 这是因为结果的数量很大,所以dfs返回所有结果会TLE,所以只是返回数量,用dp进行memoization.

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
class Solution {
public int minCut(String ss) {
char[] s = ss.toCharArray();
int n = s.length;
if (n == 0) return 0;
int[] f = new int[n+1];
f[0] = 0;
boolean[][] isPalin = calPalin(s);
int i, j;

// f: 0 - n; index: 0 - (n-1); len: 1-n;
for (i = 1; i <= n; ++i) {
f[i] = Integer.MAX_VALUE;
for (j = 0; j < i; j++) {
if (isPalin[j][i - 1]) {
f[i] = Math.min(f[i], f[j] + 1);
}
}
}

return f[n] - 1;
}

private boolean[][] calPalin(char[] s) {
int n = s.length;
boolean[][] f = new boolean[n][n];
int i, j, c;
for (i = 0; i < n; ++i) {
for (j = i; j < n; ++j) {
f[i][j] = false;
}
}

// odd length, c: center char
for (c = 0; c < n; ++c) {
i = j = c;
while (i >= 0 && j < n && s[i] == s[j]) {
f[i][j] = true;
--i;
++j;
}
}

// even length, c: center char
for (c = 0; c < n; ++c) {
i = c;
j = c+1;
while (i >= 0 && j < n && s[i] == s[j]) {
f[i][j] = true;
--i;
++j;
}
}

return f;
}
}