Given a string, a partitioning of the string is a palindrome partitioning if every substring of the partition is a palindrome. For example, “aba|b|bbabb|a|b|aba” is a palindrome partitioning of “ababbbabbababa”.
bool isPallindrome(int i, int j, string str)
{
while(i < j)
{
if(str[i] != str[j])
return false;
i++;
j--;
}
return true;
}
int solve(int i, int j, string str)
{
if(i>=j)return 0;
if(isPallindrome(i,j,str))return 0;
int ans=INT_MAX;
for(int k=i;k<=j-1;k++)
{
int tempAns = solve(i,k,str)+solve(k+1,j,str)+1;
ans=min(ans,tempAns);
}
return ans;
}
int palindromicPartition(string str)
{
int n=str.length();
return solve(0,n-1,str);
}Note : Memoization will give TLE in most of the platforms since there is a more optimized approach
int dp[501][501];
bool isPallindrome(int i, int j, string str)
{
while(i < j)
{
if(str[i] != str[j])
return false;
i++;
j--;
}
return true;
}
int solve(int i, int j, string str)
{
if(i>=j)return 0;
if(isPallindrome(i,j,str))return 0;
if(dp[i][j]!=-1)
return dp[i][j];
int ans=INT_MAX;
for(int k=i;k<=j-1;k++)
{
int tempAns = solve(i,k,str)+solve(k+1,j,str)+1;
ans=min(ans,tempAns);
}
return dp[i][j]=ans;
}
int palindromicPartition(string str)
{
int n=str.length();
memset(dp,-1,sizeof(dp));
return solve(0,n-1,str);
} int dp[501][501];
bool isPallindrome(int i, int j, string str)
{
while(i < j)
{
if(str[i] != str[j])
return false;
i++;
j--;
}
return true;
}
int solve(int i, int j, string str)
{
if(i>=j)return 0;
if(isPallindrome(i,j,str))return 0;
if(dp[i][j]!=-1)
return dp[i][j];
int ans=INT_MAX;
for(int k=i;k<=j-1;k++)
{
int left,right;
if(dp[i][k]!=-1)
left=dp[i][k];
else left=solve(i,k,str);
dp[i][k]=left;
if(dp[k+1][j]!=-1)
right=dp[k+1][j];
else right=solve(k+1,j,str);
dp[k+1][j]=right;
int tempAns = left + right +1;
ans=min(ans,tempAns);
}
return dp[i][j]=ans;
}
int palindromicPartition(string str)
{
int n=str.length();
memset(dp,-1,sizeof(dp));
return solve(0,n-1,str);
}int dp[2000][2000];
bool isPallindrome(string &str,int i, int j)
{
while(i < j)
{
if(str[i] != str[j])
return false;
i++;
j--;
}
return true;
}
int solve(int i, int j, string &str)
{
if(i>=j)return 0;
if(dp[i][j]!=-1)
return dp[i][j];
if(isPallindrome(str, i, j)){
dp[i][j]=0;
return 0;
}
int ans=INT_MAX;
for(int k=i;k<=j-1;k++)
{
/*An Optimization: We will make the partition only if the string till the partition
(till Kth position) is a valid palindrome. Because the question states that all
partition must be a valid palindrome. If we dont check this, we will have to
perform recursion on the left subproblem too (solve(str, i, k)) and we will waste
a lot of time on subproblems that is not required. Without this the code will give
correct answer but TLE on big test cases. */
if(isPallindrome(str, i, k)){
int tempAns = 1+solve(k+1, j, str);
ans = min(ans, tempAns);
}
}
return dp[i][j]=ans;
}
int minCut(string str) {
int n=str.length();
memset(dp,-1,sizeof(dp));
return solve(0,n-1,str);
}