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.
动态规划。
设f(n)表示s的前n个字符组成的子串最少被切分为回文子串的数目,那么
f(n) = min{f(k) + 1, s[k .. n]是回文,其中0 < k <=n}
这个过程需要多次判断s[k .. n]是否是回文,我么可以使用备忘录的方法将s[k..n]是否是回文记录下来,以避免重复判断。
p(i, j) = p(i + 1, j - 1), 如果s[i] = s[j]; 否则p(i, j) = false
class Solution {
public:
bool isPalindrome(string &s, vector<vector<int>> &r, int i, int j) {
int &ans = r[i][j];
if (ans < 0) {
if (i >= j) ans = 1;
else if (s[i] != s[j]) ans = 0;
else ans = isPalindrome(s, r, i + 1, j - 1);
}
return ans == 1;
}
int minCut(string s) {
int n = s.length();
if (0 == n) return 0;
vector<vector<int>> r(n, vector<int>(n, -1));
// dp[i] is the minimum cuts needed for s[1..i]
vector<int> dp(n + 1, 0);
for (int i = 1; i <= n; i++) {
dp[i] = 1 << 30;
for (int j = i - 1; j >= 0; j--) {
if (dp[j] + 1 < dp[i] && isPalindrome(s, r, j, i - 1))
dp[i] = dp[j] + 1;
}
}
return dp[n] - 1;
}
};