Posted on 2022-12-15 16:37
Uriel 阅读(55)
评论(0) 编辑 收藏 引用 所属分类:
DP 、
闲来无事重切Leet Code
裸的最长公共子序列,复杂度O(mn)
1 #1143
2 #Runtime: 255 ms (Beats 94.79%)
3 #Memory: 21.6 MB (Beats 79.65%)
4
5 class Solution(object):
6 def longestCommonSubsequence(self, text1, text2):
7 """
8 :type text1: str
9 :type text2: str
10 :rtype: int
11 """
12 dp = [[0] * (len(text2) + 1) for _ in range(len(text1) + 1)]
13 for i in range(1, len(text1) + 1):
14 for j in range(1, len(text2) + 1):
15 if text1[i - 1] == text2[j - 1]:
16 dp[i][j] = dp[i-1][j-1] + 1
17 else:
18 dp[i][j] = max(dp[i-1][j], dp[i][j - 1])
19 return dp[len(text1)][len(text2)]
只开两个一维dp数组的版本:
1 #1143
2 #Runtime: 222 ms Beats 99.2%)
3 #Memory: 13.6 MB (Beats 96.7%)
4
5 class Solution(object):
6 def longestCommonSubsequence(self, text1, text2):
7 """
8 :type text1: str
9 :type text2: str
10 :rtype: int
11 """
12 dp = [0] * (len(text2) + 1)
13 dp_pre = [0] * (len(text2) + 1)
14 for i in range(1, len(text1) + 1):
15 for j in range(1, len(text2) + 1):
16 if text1[i - 1] == text2[j - 1]:
17 dp[j] = dp_pre[j-1] + 1
18 else:
19 dp[j] = max(dp_pre[j], dp[j - 1])
20 dp_pre = dp
21 dp = [0] * (len(text2) + 1)
22 return dp_pre[len(text2)]