Skip to content

Commit d3fb5b6

Browse files
authored
Create 01 - Recursive Approach (caused TLE).cpp
1 parent d0b979e commit d3fb5b6

File tree

1 file changed

+29
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)