mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 1143.最长公共子序列.md
This commit is contained in:
@ -198,21 +198,49 @@ class Solution {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
2维DP
|
||||||
```python
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
|
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
|
||||||
len1, len2 = len(text1)+1, len(text2)+1
|
# 创建一个二维数组 dp,用于存储最长公共子序列的长度
|
||||||
dp = [[0 for _ in range(len1)] for _ in range(len2)] # 先对dp数组做初始化操作
|
dp = [[0] * (len(text2) + 1) for _ in range(len(text1) + 1)]
|
||||||
for i in range(1, len2):
|
|
||||||
for j in range(1, len1): # 开始列出状态转移方程
|
# 遍历 text1 和 text2,填充 dp 数组
|
||||||
if text1[j-1] == text2[i-1]:
|
for i in range(1, len(text1) + 1):
|
||||||
|
for j in range(1, len(text2) + 1):
|
||||||
|
if text1[i - 1] == text2[j - 1]:
|
||||||
|
# 如果 text1[i-1] 和 text2[j-1] 相等,则当前位置的最长公共子序列长度为左上角位置的值加一
|
||||||
dp[i][j] = dp[i - 1][j - 1] + 1
|
dp[i][j] = dp[i - 1][j - 1] + 1
|
||||||
else:
|
else:
|
||||||
|
# 如果 text1[i-1] 和 text2[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])
|
||||||
return dp[-1][-1]
|
|
||||||
```
|
|
||||||
|
|
||||||
|
# 返回最长公共子序列的长度
|
||||||
|
return dp[len(text1)][len(text2)]
|
||||||
|
|
||||||
|
```
|
||||||
|
1维DP
|
||||||
|
```python
|
||||||
|
class Solution:
|
||||||
|
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
|
||||||
|
m, n = len(text1), len(text2)
|
||||||
|
dp = [0] * (n + 1) # 初始化一维DP数组
|
||||||
|
|
||||||
|
for i in range(1, m + 1):
|
||||||
|
prev = 0 # 保存上一个位置的最长公共子序列长度
|
||||||
|
for j in range(1, n + 1):
|
||||||
|
curr = dp[j] # 保存当前位置的最长公共子序列长度
|
||||||
|
if text1[i - 1] == text2[j - 1]:
|
||||||
|
# 如果当前字符相等,则最长公共子序列长度加一
|
||||||
|
dp[j] = prev + 1
|
||||||
|
else:
|
||||||
|
# 如果当前字符不相等,则选择保留前一个位置的最长公共子序列长度中的较大值
|
||||||
|
dp[j] = max(dp[j], dp[j - 1])
|
||||||
|
prev = curr # 更新上一个位置的最长公共子序列长度
|
||||||
|
|
||||||
|
return dp[n] # 返回最后一个位置的最长公共子序列长度作为结果
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
```Go
|
```Go
|
||||||
|
Reference in New Issue
Block a user