// C# implementation for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Define the dp table globally
static int [,]dp = new int[505,505];
static int [,]choose = new int[502,502];
// Recursive function to calculate the dp
// values for range [L, R]
static int calc(int l, int r, string s)
{
// The range is odd length
if (Math.Abs(r - l) % 2 == 0) {
return 0;
}
if (l > r) {
return dp[l,r] = 1;
}
// The state is already calculated
if (dp[l,r] != -1) {
return dp[l,r];
}
// If the length is 2
if ((r - l) == 1) {
if (s[l] == s[r]) {
dp[l,r] = 1;
}
else {
dp[l,r] = 0;
}
return dp[l,r];
}
// Total answer for this state
int ans = 0;
for (int k = l + 1; k <= r; k += 2) {
// Variable to store the current answer.
int temp = 1;
// Remove characters s[l] and s[i].
if (s[l] == s[k]) {
temp = calc(l + 1, k - 1, s)
* calc(k + 1, r, s)
* choose[(r - l + 1) / 2,(r - k) / 2];
ans += temp;
}
}
return dp[l,r] = ans;
}
static int waysToClearString(string S)
{
// Initialize all the states of dp to -1
for(int i=0;i<505;i++){
for(int j=0;j<505;j++)
dp[i,j] = -1;
}
// Calculate all Combinations
int n = S.Length;
choose[0,0] = 1;
for (int i = 1; i <= n / 2; ++i) {
choose[i,0] = 1;
for (int j = 1; j <= i; ++j) {
choose[i,j]
= (choose[i - 1,j]
+ choose[i - 1,j - 1]);
}
}
return calc(0, n - 1, S);
}
// Driver Code
public static void Main()
{
string S = "aabccb";
Console.Write(waysToClearString(S));
}
}
// This code is contributed by ipg2016107.