思想:
- 定义g[i][j]:text1的前i位和text2的前j位的最长公共子序列长度。
- 递推公式:如果text[i]==text[j],那么只需要看g[i-1][j-1]即可,此时g[i][j]=g[i-1][j-1]+1。如果text[i]!=text[j],那么g[i][j]=max(g[i-1][j],g[i][j-1],g[i-1][j-1])
- 数组初始化:由g[i-1][j],g[i][j-1],g[i-1][j-1]推及g[i][j],即由左上角向右下角推(两层for循环都是从小到大遍历,推荐博客:力扣---最长回文子串---二维动态规划-CSDN博客(考察for循环遍历顺序)),需要初始化第0行和第0列。
代码:
C++:
class Solution {
public:int longestCommonSubsequence(string text1, string text2) {int len1=text1.size();int len2=text2.size();vector<vector<int>> g(len1,vector<int>(len2,0));//g[0][0]if(text1[0]==text2[0]){g[0][0]=1;}else{g[0][0]=0;}//g[0][i]+g[i][0]for(int i=1;i<len2;i++){if(text1[0]==text2[i]){g[0][i]=1;}else{g[0][i]=g[0][i-1];}}//cout<<"***"<<endl;for(int i=1;i<len1;i++){if(text1[i]==text2[0]){g[i][0]=1;}else{g[i][0]=g[i-1][0];}}for(int i=1;i<len1;i++){for(int j=1;j<len2;j++){if(text1[i]==text2[j]){g[i][j]=g[i-1][j-1]+1;}else{g[i][j]=max(g[i-1][j],g[i][j-1]);g[i][j]=max(g[i][j],g[i-1][j-1]);}}}return g[len1-1][len2-1];}
};
Python:
class Solution:def longestCommonSubsequence(self, text1: str, text2: str) -> int:len1=len(text1)len2=len(text2)g=[[0 for _ in range(len2)] for _ in range(len1)]if text1[0]==text2[0]:g[0][0]=1else:g[0][0]=0for i in range(1,len2):if text1[0]==text2[i]:g[0][i]=1else:g[0][i]=g[0][i-1]for i in range(1,len1):if text1[i]==text2[0]:g[i][0]=1else:g[i][0]=g[i-1][0]for i in range(1,len1):for j in range(1,len2):if text1[i]==text2[j]:g[i][j]=g[i-1][j-1]+1else:g[i][j]=max(g[i-1][j],g[i][j-1])g[i][j]=max(g[i][j],g[i-1][j-1])return g[len1-1][len2-1]