From db93191fc0326a419161324abcf234c53b22e1b5 Mon Sep 17 00:00:00 2001 From: jasper Date: Sun, 21 Jun 2020 18:41:07 -0400 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0C++=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...61\345\255\220\345\272\217\345\210\227.md" | 44 ++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git "a/\345\212\250\346\200\201\350\247\204\345\210\222\347\263\273\345\210\227/\346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227.md" "b/\345\212\250\346\200\201\350\247\204\345\210\222\347\263\273\345\210\227/\346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227.md" index 98b06af..7bb6031 100644 --- "a/\345\212\250\346\200\201\350\247\204\345\210\222\347\263\273\345\210\227/\346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227.md" +++ "b/\345\212\250\346\200\201\350\247\204\345\210\222\347\263\273\345\210\227/\346\234\200\351\225\277\345\205\254\345\205\261\345\255\220\345\272\217\345\210\227.md" @@ -121,9 +121,51 @@ else: ![labuladong](../pictures/labuladong.jpg) +[labuladong](https://github.com/labuladong) 提供Python解法代码: +```python +def longestCommonSubsequence(str1, str2) -> int: + m, n = len(str1), len(str2) + # 构建 DP table 和 base case + dp = [[0] * (n + 1) for _ in range(m + 1)] + # 进行状态转移 + for i in range(1, m + 1): + for j in range(1, n + 1): + if str1[i - 1] == str2[j - 1]: + # 找到一个 lcs 中的字符 + dp[i][j] = 1 + dp[i-1][j-1] + else: + dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + + return dp[-1][-1] +``` + +[Jinglun Zhou](https://github.com/Jasper-Joe) 提供C++解法代码: + +```CPP +class Solution { +public: + int longestCommonSubsequence(string str1, string str2) { + int m=str1.size(), n=str2.size(); + // 构建DP table 和 base case + vector> dp(m+1,vector(n+1)); + // dp[i][j]表示: 字符串str1[0:i]和字符串str2[0:j]的最大公共子序列 + // 进行状态转移 + for(int i=1;i<=m;i++) + for(int j=1;j<=n;j++) + if(str1[i-1]==str2[j-1]) // 两个字符相等,必然可以构成子问题的最优解 + // 找到一个lcs中的字符 + dp[i][j]=1+dp[i-1][j-1]; + else //如果两个字符不相等,我们往前看一个字符 + //寄希望于str1[i-2]和str2[j-1]相等,或者str1[i-1]和str2[j-2] + //如果他们两个当中有任何一个可以匹配, 我们就有机会更新当前dp值 + dp[i][j]=max(dp[i-1][j],dp[i][j-1]); + return dp[m][n]; // 根据dp的定义,答案就存储在dp[m][n]中 + } +}; +``` [上一篇:动态规划之正则表达](../动态规划系列/动态规划之正则表达.md) [下一篇:学习算法和刷题的思路指南](../算法思维系列/学习数据结构和算法的高效方法.md) -[目录](../README.md#目录) \ No newline at end of file +[目录](../README.md#目录) -- GitLab