#include <vector>
#include <iostream>
#include <climits>
using namespace std;
/*
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.
*/
// Time Complexity is O(N^3)
int minCut(string s) {
// minCut(i, j) = minCut(i, k) + minCut(k + 1, j) + 1;
// if s[i, j] is palindrome, minCut(i, j) = 0;
// we thus need to 2D array to make the palindrome. and a 2d array to calculate the minvalue.
int n = s.size();
vector< vector<bool> > P(n, vector<bool>(n, false));
vector< vector<int> > minCut(n, vector<int>(n, INT_MAX));
for(int i = 0; i < n; ++i) {
P[i][i] = true;
minCut[i][i] = 0;
}
for(int L = 2; L <= n; ++L) {
for(int start = 0; start < n - L + 1; ++start) {
int end = start + L - 1;
if(L == 2) {
P[start][end] = (s[start] == s[end]);
} else {
P[start][end] = ((s[start] == s[end]) && P[start + 1][end - 1]);
}
if(P[start][end] == true) minCut[start][end] = 0;
else {
for(int k = start; k < end; ++k) {
minCut[start][end] = min(minCut[start][end], minCut[start][k] + minCut[k+1][end] + 1);
}
}
}
}
return minCut[0][n-1];
}
int main(void) {
cout << minCut("aabaa") << endl;
}
LeetCode 132. Palindrome Partitioning II
最新推荐文章于 2021-12-18 21:08:14 发布