Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0a742d8

Browse files
Update 1143.最长公共子序列.md
1 parent 8fb1697 commit 0a742d8

File tree

1 file changed

+37
-9
lines changed

1 file changed

+37
-9
lines changed

‎problems/1143.最长公共子序列.md‎

Lines changed: 37 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -198,21 +198,49 @@ class Solution {
198198
```
199199

200200
Python:
201-
201+
2维DP
202202
```python
203203
class Solution:
204204
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
205-
len1, len2 = len(text1)+1, len(text2)+1
206-
dp = [[0 for _ in range(len1)] for _ in range(len2)] # 先对dp数组做初始化操作
207-
for i in range(1, len2):
208-
for j in range(1, len1): # 开始列出状态转移方程
209-
if text1[j-1] == text2[i-1]:
210-
dp[i][j] = dp[i-1][j-1]+1
205+
# 创建一个二维数组 dp,用于存储最长公共子序列的长度
206+
dp = [[0] * (len(text2) + 1) for _ in range(len(text1) + 1)]
207+
208+
# 遍历 text1 和 text2,填充 dp 数组
209+
for i in range(1, len(text1) + 1):
210+
for j in range(1, len(text2) + 1):
211+
if text1[i - 1] == text2[j - 1]:
212+
# 如果 text1[i-1] 和 text2[j-1] 相等,则当前位置的最长公共子序列长度为左上角位置的值加一
213+
dp[i][j] = dp[i - 1][j - 1] + 1
211214
else:
212-
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
213-
return dp[-1][-1]
215+
# 如果 text1[i-1] 和 text2[j-1] 不相等,则当前位置的最长公共子序列长度为上方或左方的较大值
216+
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
217+
218+
# 返回最长公共子序列的长度
219+
return dp[len(text1)][len(text2)]
220+
214221
```
222+
1维DP
223+
```python
224+
class Solution:
225+
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
226+
m, n = len(text1), len(text2)
227+
dp = [0] * (n + 1) # 初始化一维DP数组
228+
229+
for i in range(1, m + 1):
230+
prev = 0 # 保存上一个位置的最长公共子序列长度
231+
for j in range(1, n + 1):
232+
curr = dp[j] # 保存当前位置的最长公共子序列长度
233+
if text1[i - 1] == text2[j - 1]:
234+
# 如果当前字符相等,则最长公共子序列长度加一
235+
dp[j] = prev + 1
236+
else:
237+
# 如果当前字符不相等,则选择保留前一个位置的最长公共子序列长度中的较大值
238+
dp[j] = max(dp[j], dp[j - 1])
239+
prev = curr # 更新上一个位置的最长公共子序列长度
240+
241+
return dp[n] # 返回最后一个位置的最长公共子序列长度作为结果
215242

243+
```
216244

217245
Go:
218246
```Go

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /