LeetCode Solutions

516. Longest Palindromic Subsequence

Time: $O(n^2)$

Space: $O(n^2)$

			

class Solution {
 public:
  int longestPalindromeSubseq(string s) {
    const int n = s.length();
    // dp[i][j] := LPS's length in s[i..j]
    dp.resize(n, vector<int>(n));
    return lps(s, 0, n - 1);
  }

 private:
  vector<vector<int>> dp;

  int lps(const string& s, int i, int j) {
    if (i > j)
      return 0;
    if (i == j)
      return 1;
    if (dp[i][j])
      return dp[i][j];

    if (s[i] == s[j])
      dp[i][j] = 2 + lps(s, i + 1, j - 1);
    else
      dp[i][j] = max(lps(s, i + 1, j), lps(s, i, j - 1));

    return dp[i][j];
  }
};
			

class Solution {
  public int longestPalindromeSubseq(String s) {
    final int n = s.length();
    // dp[i][j] := LPS's length in s[i..j]
    dp = new int[n][n];
    return lps(s, 0, n - 1);
  }

  private int[][] dp;

  private int lps(final String s, int i, int j) {
    if (i > j)
      return 0;
    if (i == j)
      return 1;
    if (dp[i][j] > 0)
      return dp[i][j];

    if (s.charAt(i) == s.charAt(j))
      dp[i][j] = 2 + lps(s, i + 1, j - 1);
    else
      dp[i][j] = Math.max(lps(s, i + 1, j), lps(s, i, j - 1));

    return dp[i][j];
  }
}
			

class Solution:
  def longestPalindromeSubseq(self, s: str) -> int:
    # Dp(i, j) := LPS's length in s[i..j]
    @functools.lru_cache(None)
    def dp(i: int, j: int) -> int:
      if i > j:
        return 0
      if i == j:
        return 1
      if s[i] == s[j]:
        return 2 + dp(i + 1, j - 1)
      return max(dp(i + 1, j), dp(i, j - 1))

    return dp(0, len(s) - 1)