this is code of LCS, can you explain it? [code] Save & SubmitCancel
- User
this is code of LCS, can you explain it?
codeclass Solution { public int[][] memo; public int longestCommonSubsequence(String text1, String text2) { int n = text1.length(); int m = text2.length(); memo = new int[n][m]; for (int i = 0; i < n; i++) { Arrays.fill(memo[i], -1); } return dfs(0, 0, text1, text2); } public int dfs(int i, int j, String t1, String t2) { if (i == t1.length() || j == t2.length()) return 0; if (memo[i][j] != -1) return memo[i][j]; int res = 0; if (t1.charAt(i) == t2.charAt(j)) { res = Math.max(res, dfs(i+1, j+1, t1, t2) + 1); // res = Math.max(res, dfs(i+1, j, t1, t2)); // res = Math.max(res, dfs(i, j+1, t1, t2)); } else { // res = Math.max(res, dfs(i+1, j+1, t1, t2)); res = Math.max(res, dfs(i+1, j, t1, t2)); res = Math.max(res, dfs(i, j+1, t1, t2)); } memo[i][j] = res; return res; } } ```Save & SubmitCancel - Assistant
The given solution uses dynamic programming approach to solve the Longest Common Subsequence (LCS) problem.
The main idea behind the dynamic programming approach is to break down the problem into smaller sub-problems and store the results of these sub-problems to avoid recomputing them. This is done using memoization (caching) technique.
In the given code, a 2D array
memois used to store the results of previously computed sub-problems. The function is a recursive function that takes two indices and representing the current positions in the two strings and . The function returns the length of the longest common subsequence starting from these positions. - User
can you make it print LCS string?
- Assistant
Yes, we can modify the given solution to print the LCS string by keeping track of the characters that contribute to the LCS while computing the memo table. Here's the modified code:
scss