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.
题目思考:
从后往前构造二维数组isPalin,用于存储已经确定的回文子串。isPalin[i][j]==true代表s[i,...,j]是回文串。
在构造isPalin的同时使用动态规划计算从后往前的最小切分数,记录在min数组中。min[i]代表s[i,...,n-1]的最小切分数
Solution:
class Solution {
public:
int minCut(string s) {
int n = s.size();
vector<vector<bool> > isPalin(n, vector<bool>(n, false));
vector<int> min(n+1, -1); //min cut from end
for(int i = 0; i < n; i ++)
{
isPalin[i][i] = true;
}
for(int i = n-1; i >= 0; i --)
{
min[i] = min[i+1] + 1;
for(int j = i+1; j < n; j ++)
{
if(s[i] == s[j])
{
if(j == i+1 || isPalin[i+1][j-1] == true)
{
isPalin[i][j] = true;
if(j == n-1)
min[i] = 0;
else if(min[i] > min[j+1]+1)
min[i] = min[j+1] + 1;
}
}
}
}
return min[0];
}
};