Palindrome Partitioning II
Given A string s, partition s such that every substring of the partition are 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.
The method of dynamic programming can first get isp[i][j], that is, whether the string, from I to J is a palindrome isp[i][j]= ((s[i]==s[j)) && (j-i<=1| | ISP[I+1][J-1])) and we then determine the number of splits dp[i] represents the minimum number of splits from I to N, only a point from the middle, so that the minimum number of splits can bedp[i]=min (dp[k]+1) K=I+1......N
1 classSolution {2 Public:3 intMincut (strings) {4 5 intn=s.length ();6vector<vector<BOOL> > IsP (n,vector<BOOL> (n,false));7 8 for(inti=n-1; i>=0; i--)9 {Ten for(intj=i;j<n;j++) One { A if(s[i]==s[j]&& (j-i<=1|| isp[i+1][j-1])) isp[i][j]=true; - } - } the -vector<int> dp (n+1); -dp[n]=-1;//note the boundary conditions, indicating the dp[i] without splitting, dp[i]=dp[n]+1=0; - for(inti=n-1; i>=0; i--) + { - intmincut=Int_max; + for(intk=i+1; k<n+1; k++) A { at if(isp[i][k-1]&&mincut>dp[k]+1) - { -dp[i]=dp[k]+1; -mincut=Dp[i]; - } - } in } - to returndp[0]; + } -};
"Leetcode" Palindrome partitioning II