Skip to content

Commit

Permalink
Update 516.longest-palindromic-subsequence.md
Browse files Browse the repository at this point in the history
  • Loading branch information
azl397985856 authored Aug 11, 2021
1 parent 7be2100 commit a3e9d5c
Showing 1 changed file with 41 additions and 2 deletions.
43 changes: 41 additions & 2 deletions problems/516.longest-palindromic-subsequence.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,11 @@ base case 就是一个字符(轴对称点是本身)

## 代码

代码支持:JS,Python3


JS Code:

```js
/*
* @lc app=leetcode id=516 lang=javascript
Expand Down Expand Up @@ -116,10 +121,44 @@ var longestPalindromeSubseq = function (s) {
};
```

Python3 Code(记忆化递归):

```py
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
@cache
def dp(l,r):
if l >= r: return int(l == r)
if s[l] == s[r]:
return 2 + dp(l+1,r-1)
return max(dp(l+1, r), dp(l, r-1))
return dp(0, len(s)-1)
```

Python3 Code(普通 dp)

```py
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
n = len(s)
dp = [[0]*n for _ in range(n)]

for i in range(n-1, -1, -1):
for j in range(i, n):
if i == j:
dp[i][j] = 1
elif 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][-1]

```

**复杂度分析**

- 时间复杂度:$O(N^2)$
- 空间复杂度:$O(N^2)$
- 时间复杂度:枚举所有的状态需要 n^2 时间,状态转移需要常数的时间,因此总的时间复杂度为 $O(n^2)$
- 空间复杂度:我们使用二维 dp 存储所有状态,因此空间复杂度为 $O(n^2)$

## 相关题目

Expand Down

0 comments on commit a3e9d5c

Please sign in to comment.