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.
解题思路:
这道题的重点不仅在于动态规划,还在于回文串的判断。
class Solution {
public:
int minCut(string s)
{
int len = s.size() ;
vector<int> dp = vector<int>(len + 1 , INT_MAX) ;
vector<vector<int>> palin(len , vector<int>(len , 0)) ;
dp[0] = -1 ;
for(int i = 0 ; i < len ; ++i)
{
palin[i][i] = 1 ;
if(i < len - 1 && s[i] == s[i + 1]) palin[i][i + 1] = 1 ;
}
for(int l = 3 ; l <= len ; ++l)
{
for(int i = 0 ; i < len + 1 - l ; ++i)
{
if(s[i] == s[i + l - 1] && palin[i + 1][i + l - 2]) palin[i][i + l - 1] = 1 ;
}
}
for(int i = 1 ; i <= len ; ++i)
{
for(int j = 0 ; j < i ; ++j)
{
if(palin[j][i - 1] == 1)
dp[i] = min(dp[i] , 1 + dp[j]) ;
if(dp[i] == 0) break ;
}
}
return dp[len] ;
}
};