题目描述(Hard)
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.
题目链接
https://leetcode.com/problems/palindrome-partitioning-ii/description/
Example 1:
Input: "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
算法分析
每次从i往右扫描,每找到一个回文就算一次DP,可以转换为f(i)=[i, n-1]之间的最小的cut数,n为字符串长度,则状态转移方程为。判断[i,j]为回文,每次从i到j比较太过于费时,可以定义状态P[i][j]=true,如果[i,j]为回文,那么P[i][j]=str[i]==str[j] && P[i+1][j-1]。
提交代码:
class Solution {
public:
int minCut(string s) {
const int n = s.size();
int f[n + 1];
bool p[n][n];
fill_n(&p[0][0], n * n, false);
for (int i = 0; i <= n; ++i)
f[i] = n - i - 1;
for (int i = n - 1; i >= 0; --i) {
for (int j = i; j < n; ++j) {
if (s[i] == s[j] && (j - i < 2 || p[i + 1][j - 1])) {
p[i][j] = true;
f[i] = min(f[i], f[j + 1] + 1);
}
}
}
return f[0];
}
};