// C# program to memoize
// recursive implementation of LCS problem
using System;
class GFG
{
static readonly int maximum = 1000;
// Returns length of LCS for
// X[0..m-1], Y[0..n-1]
// memoization applied in
// recursive solution
static int lcs(String X, String Y,
int m, int n, int [,]dp)
{
// base case
if (m == 0 || n == 0)
{
return 0;
}
// if the same state has already been
// computed
if (dp[m - 1, n - 1] != -1)
{
return dp[m - 1, n - 1];
}
// if equal, then we store the value
// of the function call
if (X[m - 1] == Y[n - 1])
{
// store it in arr to avoid
// further repetitive work
// in future function calls
dp[m - 1,
n - 1] = 1 + lcs(X, Y, m - 1,
n - 1, dp);
return dp[m - 1, n - 1];
}
else
{
// store it in arr to avoid
// further repetitive work
// in future function calls
dp[m - 1,
n - 1] = Math.Max(lcs(X, Y, m, n - 1, dp),
lcs(X, Y, m - 1, n, dp));
return dp[m - 1, n - 1];
}
}
// Driver Code
public static void Main(String[] args)
{
String X = "AGGTAB";
String Y = "GXTXAYB";
int m = X.Length;
int n = Y.Length;
int [,]dp = new int[m, maximum];
// assign -1 to all positions
for(int i = 0; i < m; i++)
{
for(int j = 0; j < maximum; j++)
{
dp[i, j] = -1;
}
}
Console.WriteLine("Length of LCS: " +
lcs(X, Y, m, n, dp));
}
}
// This code is contributed by PrinciRaj1992