https://oj.leetcode.com/problems/palindrome-partitioning-ii/
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.
For example, given s = "aab"
,
Return 1
since the palindrome partitioning ["aa","b"]
could be produced using 1 cut.
这一题也是可以用到上一题Palindrome Partitioning介绍的那个做法去进行优化的。当然,最核心的算法是另一个dp工程式:
g(j)最初始为j - 1
g(j) = min(g[k] + 1, g(j)) k == 1 ... j - 1 when f(k, j) == true (f(i,j)的定义可以参见Palindrome Partitioning那一题)
或者g(j) = 0 if f(0, j) == true
现在开始解释递推式,g(j)表示的是S[0..j] 的mincut值,最初始为j - 1的原因是worst case肯定就是j个字母之间各砍一刀,也就是j - 1刀。第二个条件是如果本身是一个palindrome的话就不用砍了。如果不符合第二个条件,那么就要先做某种一刀切,这一刀的右边是一个palindrome,左边呢,则是之前的mincut的子结果g(k),所以这个时候的结果就是g(k) + 1。然后把所有这样的一刀找出来,看看哪个是最小的,就是当前位置的子结果了。
最后返回g(S.length() - 1)就好。
下面给出代码。
public int minCut(String s) {
boolean[][] dp = new boolean[s.length()][s.length()];
for(int dist = 0; dist < s.length(); dist++){
for(int i = 0; i < s.length() - dist; i++){
dp[i][i + dist] = s.charAt(i) == s.charAt(i + dist) && (dist <= 1 ? true : dp[i + 1][i + dist - 1]);
}
}
int[] cutter = new int[s.length()];
for(int i = 0; i < s.length(); i++){
if(dp[0][i]){
cutter[i] = 0;
continue;
}
cutter[i] = i;
for(int j = 0; j < i; j++){
if(dp[j + 1][i]){
cutter[i] = Math.min(cutter[j] + 1, cutter[i]);
}
}
}
return cutter[s.length() - 1];
}
事实上把前面几行去掉然后把dp[j + 1][i]换成上一题的isValid函数照样也是可行的。