Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RitamChakraborty/e7e4f076a7ee6ce62d5dc64141014a7a to your computer and use it in GitHub Desktop.
Save RitamChakraborty/e7e4f076a7ee6ce62d5dc64141014a7a to your computer and use it in GitHub Desktop.
Longest Common Subsequence problem using recursion with memorization.
import java.util.Arrays;
public class LongestCommonSubsequenceWithMemorization {
private static char[] A;
private static char[] B;
private static int[][] arr;
private static int longestCommonSubsequent(int i, int j) {
if (i == A.length || j == B.length) {
return 0;
} else if (arr[i][j] != -1) {
return arr[i][j];
} else if (A[i] == B[j]) {
arr[i][j] = 1 + longestCommonSubsequent(i + 1, j + 1);
return arr[i][j];
} else {
arr[i][j] = Integer.max(longestCommonSubsequent(i + 1, j), longestCommonSubsequent(i, j + 1));
return arr[i][j];
}
}
public static void main(String[] args) {
A = "bd".toCharArray();
B = "abcd".toCharArray();
arr = new int[A.length][B.length];
Arrays.stream(arr).forEach(i -> Arrays.fill(i, -1));
System.out.println(longestCommonSubsequent(0, 0));
System.out.println("Memory: " + Arrays.deepToString(arr));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment