以leetcode1143题为例:
首先是使用二维数组解题
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
m,n=len(text1),len(text2)
dp=[[0]*(n+1) for _ in range(m+1)]
for i in range(1,m+1):
for j in range(1,n+1):
if text1[i-1]==text2[j-1]:
dp[i][j]=dp[i-1][j-1]+1
else:
dp[i][j]=max(dp[i-1][j],dp[i][j-1])
return dp[m][n]
由于dp过程只需要上一行和本行的dp值,所以我们只需要两行向量就行。
选取更短的作为列
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
m,n=len(text1),len(text2)
if m<n:
return self.longestCommonSubsequence(text2,text1)
pre=[0]*(n+1)
cur=[0]*(n+1)
for i in range(1,m+1):
for j in range(1,n+1):
if text1[i-1]==text2[j-1]:
cur[j]=pre[j-1]+1
else:
cur[j]=max(pre[j],cur[j-1])
pre=cur.copy()
return cur[n]
上一行的数组每次只用到一个数,所以我们可以用一个数来表示。
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
m,n=len(text1),len(text2)
if m<n:
return self.longestCommonSubsequence(text2,text1)
cur=[0]*(n+1)
for i in range(1,m+1):
pre=0
for j in range(1,n+1):
tmp=cur[j]
if text1[i-1]==text2[j-1]:
cur[j]=pre+1
else:
cur[j]=max(cur[j],cur[j-1])
pre=tmp
return cur[n]