前言
date: 2021.10.16 又穷又菜 有没有女朋友… 打球又打不好,肌肉又很小! 何时才能变得更好呢? 不说了,明天早起学习! “什么,又睡过头了?!!!”
汇总: 每日一题系列_算法提升 题目: 516. 最长回文子序列(leetcode)
题目
题解
参考官方题解 首先考虑边界条件,当边界 i = j 时,长度为1. 然后 i, j 向两边扩展,
- 当
s
[
i
]
=
=
s
[
j
]
s[i]==s[j]
s[i]==s[j]时,
d
p
[
i
]
[
j
]
=
d
p
[
i
+
1
]
[
j
?
1
]
+
2
dp[i][j] = dp[i+1][j-1]+2
dp[i][j]=dp[i+1][j?1]+2
- 当
s
[
i
]
!
=
s
[
j
]
s[i]!=s[j]
s[i]!=s[j]时,
s
[
i
]
s[i]
s[i] 和
s
[
j
]
s[j]
s[j] 不可能同时出现在同个回文串中,故
d
p
[
i
]
[
j
]
=
m
a
x
(
d
p
[
i
+
1
]
[
j
]
,
d
p
[
i
]
[
j
?
1
]
)
dp[i][j]=max(dp[i+1][j], dp[i][j-1])
dp[i][j]=max(dp[i+1][j],dp[i][j?1])
class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = s.length();
vector<vector<int>> dp(n, vector<int> (n));
for (int i = 0; i < n; i++)
dp[i][i] = 1;
for (int i = n - 1; i >= 0; i--)
for (int j = i + 1; j < n; j++) {
if (s[i] == s[j])
dp[i][j] = dp[i + 1][j - 1] + 2;
else
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
}
return dp[0][n - 1];
}
};
|