Skip to content

Commit 77e0a39

Browse files
authored
Create 01 - Recursive Approach (caused TLE).cpp
1 parent a5788e4 commit 77e0a39

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
public:
3+
// Recursive helper function to solve the problem
4+
// Parameters:
5+
// - str: the original string
6+
// - revStr: the reversed string
7+
// - i: current index in the original string
8+
// - j: current index in the reversed string
9+
int solve(string str, string revStr, int i, int j) {
10+
// Base case: if either index goes out of bounds, return 0
11+
if (i >= str.length() || j >= revStr.length())
12+
return 0;
13+
14+
// Initialize the answer variable
15+
int ans = 0;
16+
17+
// If the characters match, add 1 to the result and move to the next indices
18+
if (str[i] == revStr[j])
19+
return 1 + solve(str, revStr, i + 1, j + 1);
20+
else {
21+
// If the characters do not match, find the maximum result by:
22+
// 1. Skipping the current character in the original string
23+
// 2. Skipping the current character in the reversed string
24+
ans = max(solve(str, revStr, i + 1, j), solve(str, revStr, i, j + 1));
25+
}
26+
27+
// Return the computed answer
28+
return ans;
29+
}
30+
31+
// Function to calculate the longest palindromic subsequence
32+
int longestPalindromeSubseq(string str) {
33+
// Create a reversed version of the input string
34+
string revStr = str;
35+
reverse(revStr.begin(), revStr.end());
36+
37+
// Start solving from the first indices of both strings
38+
return solve(str, revStr, 0, 0);
39+
}
40+
};

0 commit comments

Comments
 (0)