Skip to content

Commit 0b1c130

Browse files
authored
Create 02 - Top-Down | DP | Approach.cpp
1 parent d3fb5b6 commit 0b1c130

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
public:
3+
// Helper function to recursively find the length of the longest common subsequence with memoization
4+
int solve(string &text1, string &text2, int i, int j, vector<vector<int>>& dp) {
5+
// Base case: if either string is exhausted, no subsequence is possible
6+
if (i >= text1.length() || j >= text2.length()) return 0;
7+
8+
// Check if the result for this state has already been computed
9+
if (dp[i][j] != -1) return dp[i][j];
10+
11+
int ans = 0; // Initialize the answer for the current state
12+
13+
// Case 1: Characters match, include them in the subsequence
14+
if (text1[i] == text2[j])
15+
return dp[i][j] = 1 + solve(text1, text2, i + 1, j + 1, dp);
16+
else {
17+
// Case 2: Characters don't match, explore two possibilities:
18+
// a) Skip the current character of text1
19+
// b) Skip the current character of text2
20+
// Take the maximum of these two possibilities
21+
ans = max(solve(text1, text2, i + 1, j, dp), solve(text1, text2, i, j + 1, dp));
22+
}
23+
24+
// Store the computed result in the memoization table
25+
return dp[i][j] = ans;
26+
}
27+
28+
// Main function to compute the longest common subsequence
29+
int longestCommonSubsequence(string text1, string text2) {
30+
// Create a 2D vector for memoization initialized with -1
31+
// dp[i][j] stores the result of solve for indices i and j
32+
vector<vector<int>> dp(text1.size() + 1, vector<int>(text2.size() + 1, -1));
33+
34+
// Start the recursive computation from the beginning of both strings
35+
return solve(text1, text2, 0, 0, dp);
36+
}
37+
};

0 commit comments

Comments
 (0)