Problem 40: Palindrome Partitioning Minimum Cuts
Problem Statement: Given a string, partition it into substrings such that every substring is a palindrome. Determine the minimum number of cuts needed for such a partition. If the string is already a palindrome, no cuts are needed.
Input
A single line containing the string.
Output
Print the minimum number of cuts needed.
Examples
Input:
aab
Output:
1
Solution Explanation
Method 1: Use dynamic programming to precompute a 2D table of palindromic substrings and then use another DP to calculate the minimum cuts required. Method 2: Use recursion with memoization to try all possible palindrome partitions and choose the minimum cut count.
Solution in C++
#include
#include
#include
using namespace std;
bool isPalindrome(const string &s, int i, int j) {
while(i < j){
if(s[i] != s[j]) return false;
i++; j--;
}
return true;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
string s; cin >> s;
int n = s.size();
vector cuts(n, 0);
vector> pal(n, vector(n, false));
for (int i = 0; i < n; i++) {
pal[i][i] = true;
}
for (int len = 2; len <= n; len++){
for (int i = 0; i <= n - len; i++){
int j = i + len - 1;
if(s[i] == s[j]) {
pal[i][j] = (len == 2) ? true : pal[i+1][j-1];
}
}
}
for (int i = 0; i < n; i++){
if(pal[0][i]) {
cuts[i] = 0;
} else {
int minCut = i;
for (int j = 0; j < i; j++){
if(pal[j+1][i] && 1 + cuts[j] < minCut)
minCut = 1 + cuts[j];
}
cuts[i] = minCut;
}
}
cout << cuts[n-1] << "
";
return 0;
}