动态规划。
1. palindrome[i][j]==true, 表示s[i, ..., j] (i<=j)为回文。
将其初始化为false. 有动态方程:
if (s[i]==s[j] && (j-i<=2 || palindrome[i+1][j-1]))
{
palindrome[i][j] = true;
}
2. dp[i]标志子串s.substr(i)的minCuts
将其初始化为dp[i] = s.size() - i - 1, 亦即dp[len-1] = len - (len-1) - 1 = 0, ..., dp[0] = len - 1(整个串需要切n-1次,切成n个字符). 有动态方程
dp[i] = min(dp[i], dp[j+1] + 1); // i<=j<n && s[i, ..., j]为回文串
代码:
class Solution
{
public:
int minCut(string s)
{
vector<vector<bool>> palindrome(s.size(), vector<bool>(s.size(), false));
int dp[s.size()+1];
for (int i = 0; i < s.size()+1; ++ i)
{
dp[i] = static_cast<int>(s.size()) - i - 1;
}
for (int i = s.size()-1; i >= 0; -- i)
{
for (int j = i; j < s.size(); ++ j)
{
if (s[i]==s[j] && (j-i<=2 || palindrome[i+1][j-1]))
{
palindrome[i][j] = true;
dp[i] = min(dp[i], dp[j+1] + 1);
}
}
}
return dp[0];
}
};