Hello Everyone,
The question is
- LeetCode
I want to know the recursion code for this problem so that I can formulate it into DP.
Here is my code
int f(vector& A, int i, int len1, vector& B, int j, int len2)
{
if(i==len1 or j==len2) return 0;
if(A[i]==B[j]) return 1 + f(A,i+1,len1,B,j+1,len2);
else return max( f(A,i,len1,B,j+1,len2), f(A,i+1,len1,B,j,len2) );
}
The problem lies in the else part of the code but somehow I am not able to visualise how to correct it due to recursive calls.
Also since the problem is same as Longest Common Substring.
how is this code working fine.
public static int LCSubStrM1(char[] X, char[] Y, int m, int n, int lcsCount) {
if (m <= 0 || n <= 0)
return lcsCount;
int lcsCount1=lcsCount;
if (X[m - 1] == Y[n - 1])
lcsCount1 = LCSubStrM1(X, Y, m - 1, n - 1, lcsCount + 1);
int lcsCount2 = LCSubStrM1(X, Y, m, n - 1, 0);
int lcsCount3 = LCSubStrM1(X, Y, m - 1, n, 0);
return Math.max(lcsCount1, Math.max(lcsCount2, lcsCount3));
}
This is my first post here. @vijju123 @anon55659401 @l_returns please help.