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.
首先通过O(n^2)初始化所有起点终点对是否是回文
判断(i,j)是否是回文可以通过(i+1,j-1)是否是回文来加速
之后通过动归完成,动归复杂度为O(n^2)

class Solution { public: int minCut(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function if(s=="")return 0; vector<vector<int> > ISP; ISP.resize(s.length()); for(int i=0;i<s.length();i++){ ISP[i].resize(s.length()); } ISP[0][0]=true; for(int i=1;i<s.length();i++){ ISP[i][i]=true; if(s[i-1]==s[i]){ ISP[i-1][i]=true; } else{ ISP[i-1][i]=false; } } for(int j=2;j<s.length();j++){ for(int i=0;i<s.length()-j;i++){ if(s[i]==s[i+j]&&ISP[i+1][i+j-1]){ ISP[i][i+j]=true; } else{ ISP[i][i+j]=false; } } } vector<int> cuts; cuts.resize(s.length()); cuts[0]=0; for(int i=1;i<s.length();i++){ cuts[i]=cuts[i-1]+1; if(ISP[0][i])cuts[i]=0; else{ for(int j=1;j<=i;j++){ if(ISP[i-j+1][i]&&cuts[i-j]+1<cuts[i]){ cuts[i]=cuts[i-j]+1; } } } } return cuts[s.length()-1]; } };