[InterviewBit] Longest Palindromic Subsequence

Longest Palindromic Subsequence

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int helper(string& s, vector<vector<int>>& dp, int l, int r) {
if(l > r) return 0;
if(l == r) return 1;
if(dp[l][r] != -1) return dp[l][r];
int& res = dp[l][r] = max(helper(s,dp,l+1,r), helper(s,dp,l,r-1));
if(s[l] == s[r]) res = max(res, helper(s,dp,l+1,r-1) + 2);
return res;
}
int Solution::solve(string A) {
int n = A.size();
vector<vector<int>> dp(n, vector<int>(n, -1));
return helper(A,dp,0,n-1);
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/26/PS/interviewbit/longest-palindromic-subsequence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.