题目描述:
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.
Example:
Input: "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
和Palindrome Partitioning类似,但是要求最小拆分次数。动态规划的思路也是一样的,但是不需要求拆分的子字符串集合,而是保留最小的拆分次数。
class Solution {
public:
int minCut(string s) {
int n=s.size();
vector<bool> row(n,false);
vector<vector<bool>> isPalin(n,row);
vector<int> min_cut(n,INT_MAX);
if(n==0) return 0;
else if(n>=1) min_cut[0]=0;
for(int j=1;j<n;j++)
{
for(int i=0;i<=j;i++)
{
if(i==j) isPalin[i][j]=true;
else if(j==i+1&&s[i]==s[j]) isPalin[i][j]=true;
else if(isPalin[i+1][j-1]&&s[i]==s[j]) isPalin[i][j]=true;
if(isPalin[i][j]==true)
{
if(i==0) min_cut[j]=0;
else min_cut[j]=min(min_cut[j],min_cut[i-1]+1);
}
}
}
return min_cut[n-1];
}
};