地址:https://oj.leetcode.com/problems/palindrome-partitioning-ii/
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.
用dp[k] 记录从下标0到下标k-1的字符串的最小cut数, dp[k] 初始化为k-1 ,并有
dp[k+1] = min(dp[k+1], 1 + dp[t]), 其中ispalindrome[ t ][ k ]==true ( 当下标t 到 下标 k之间的字符串为回文时.)
参考代码:
class Solution {
public:
int minCut(string s) {
int len = s.length();
if(len<=1)
return 0;
vector<vector<bool>>is_p(len+1, vector<bool>(len+1, false));
vector<int>dp(len+1);
for(int i = 0; i<=len; ++i)
dp[i]=i-1;
for(int i = 0; i<len; ++i)
{
for(int j = 0; j<=i; ++j)
{
if(i-j>=2 && s[i]==s[j] && is_p[j+1][i-1])
{
is_p[i][j] = is_p[j][i] = true;
dp[i+1] = min(dp[i+1], 1+dp[j]);
}
else if(i-j<2 && s[i]==s[j])
{
is_p[i][j] = is_p[j][i] = true;
dp[i+1] = min(dp[i+1], 1+dp[j]);
}
}
}
return dp[len];
}
};