Skip to content

Latest commit

 

History

History
45 lines (31 loc) · 1.39 KB

File metadata and controls

45 lines (31 loc) · 1.39 KB

LC.516 最长回文子序列

https://leetcode-cn.com/problems/longest-palindromic-subsequence/

题目描述

截屏0003-08-12 19 11 18

思路

母题在这儿呢 👉 [05] 最长回文子串

先搞明白回文子串, 再升级到非连续的子序列, 一步一步来嘛。

子序列 --> 动态规划。

回文字符串主要看两头, 如果中间已经是一个回文了, 那两头再相等, 长度就等于 中间的长度 + 2。

两头要是不相等, 那就取两端子序列的最大值。

两端子序列呢, 就是 不包含左端的[left + 1, right] 和 不包含右端的[left, right - 1]

( @cache 算作弊嘛...)

代码

class Solution(object):
    def longestPalindromeSubseq(self, s):
        @cache
        def dp(left, right):
            if left == right:
                return 1
            elif left > right:
                return 0
            if s[left] == s[right]:
                return dp(left + 1, right - 1) + 2
            return max(dp(left + 1, right), dp(left, right - 1))

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

复杂度分析

  • 时间复杂度: O(n^2)
  • 空间复杂度: O(n^2