Description:
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.
Solution:
定义cut( i , j )表示区间[i,j]之间最小的cut数,那么状态转换方程可以写成:
cut( i , j )= min { cut( i,k )+ cut( k + 1,j )} i <= k <= j
这个是二维函数,写代码会比较麻烦,因此转换成一维DP。如果每次,从 i 向右扫描,每找到一个回文就算一次DP的话,就可以转换成cut(i) =[ i ,n-1 ] 之间最小的cut数,那么状态转换方程可以写成:
cut( i )= min { cut( j + 1)+ 1} i <= j < n
时间复杂度和空间复杂度都为O(n²)。
class Solution {
public:
int minCut(string s) {
int n = s.size();
vector<int> cut(n+1);// cut[i] means the min cut in [i, n-1].
vector<vector<bool>> isPalin(n + 1, vector<bool>(n + 1, false));
for(int i = 0; i <= n; i++)//worst case
cut[i] = n - 1 - i;
for (int i = n -1 ; i >= 0; i--) {
for (int j = i; j < n; j++) {
if (s[i] == s[j] && (j - i < 2 || isPalin[i + 1][j - 1])) {
isPalin[i][j] = true;
cut[i] = min(cut[i], cut[j+1] + 1);//cut[i] = min{f[j+1]+1} i<= j < n
}
}
}
return cut[0];
}
};