思路:
参考:解答
状态定义:dp[i][j]
表示子序列s[i,j]
的最长回文子序列
状态转移:
if s[i] == s[j]:
dp[i][j] = dp[i + 1][j - 1] + 2
else:
dp[i][j] = max(dp[i][j - 1], dp[i + 1][j])
时间复杂度:O(n2)
空间复杂度:O(n2)
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
# dp[i][j]表示子序列s[i,j]的最长回文子序列
n = len(s)
dp = [[0] * n for _ in range(n)] # 全部初始化为0
for i in range(n): # 对角线表示单个字符,长度为1
dp[i][i] = 1
# 需要计算其他位置(对角线上面):从下到上,从左到右
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
if s[i] == s[j]:
dp[i][j] = dp[i + 1][j - 1] + 2
else:
dp[i][j] = max(dp[i][j - 1], dp[i + 1][j])
return dp[0][n - 1]