题目描述链接:https://leetcode-cn.com/problems/longest-common-subsequence/
解题思路:经典的LCS最长公共子序列问题:使用动态规划进行解题,
(1)状态标识dp[i][j]标识text1[0]到text1[i-1]与text2[0]到text2[j-1]的最长公共子序列.
(2)边界条件:dp[0][i]=0,dp[j][0]=0
(3)状态转移方程: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])
LeetCode解题代码:
class Solution { public: int longestCommonSubsequence(string text1, string text2) { int len1=text1.size(); int len2=text2.size(); int dp[len1+1][len2+1];//dp[i][j]保存text[0,i-1]与text[0,j-1]的LCS for(int i=0;i<=len1;++i){//边界条件处理 dp[i][0]=0; } for(int j=0;j<=len2;++j){ dp[0][j]=0; } for(int i=1;i<=len1;++i){ for(int j=1;j<=len2;++j){ 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[len1][len2]; } };
原文:https://www.cnblogs.com/zzw-/p/13399205.html