Skip to content

Commit 0279c3e

Browse files
authored
Create 02 - Top-Down | DP | Approach (caused MLE).cpp
1 parent 77e0a39 commit 0279c3e

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution {
2+
public:
3+
// Recursive function with memoization to find the longest palindromic subsequence
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+
// - dp: 2D vector for memoization to store intermediate results
10+
int solve(string str, string revStr, int i, int j, vector<vector<int>>& dp) {
11+
// Base case: if either index exceeds the string length, return 0
12+
if (i >= str.length() || j >= revStr.length())
13+
return 0;
14+
15+
// If the result for this state is already computed, return it
16+
if (dp[i][j] != -1)
17+
return dp[i][j];
18+
19+
// If characters at the current indices match, move to the next indices in both strings
20+
if (str[i] == revStr[j])
21+
return dp[i][j] = 1 + solve(str, revStr, i + 1, j + 1, dp);
22+
else {
23+
// Otherwise, take the maximum result by advancing one index at a time in either string
24+
int ans = max(solve(str, revStr, i + 1, j, dp), solve(str, revStr, i, j + 1, dp));
25+
return dp[i][j] = ans; // Store the result in the dp table
26+
}
27+
}
28+
29+
// Main function to calculate the longest palindromic subsequence
30+
int longestPalindromeSubseq(string str) {
31+
// Create a reversed copy of the original string
32+
string revStr = str;
33+
reverse(revStr.begin(), revStr.end());
34+
35+
// Initialize a 2D dp table with -1 for memoization
36+
vector<vector<int>> dp(str.length() + 1, vector<int>(revStr.length() + 1, -1));
37+
38+
// Start the recursive function with initial indices 0 and 0
39+
return solve(str, revStr, 0, 0, dp);
40+
}
41+
};

0 commit comments

Comments
 (0)