在做题中学习(93):最长公共子序列的长度
解法:动态规划(dp)
思路:图画形式说明:
附上完整代码:
#include <iostream>
#include <vector>
#include <string>
using namespace std;int func(string s1,string s2)
{//1.构建dp表int m = s1.size(),n = s2.size();vector<vector<int>> dp(m+1,vector<int>(n+1));//2.填充dp表for(int i = 1;i<=m;i++){for(int j = 1;j<=n;j++){if(s1[i-1] == s2[j-1])dp[i][j] = dp[i-1][j-1] + 1;elsedp[i][j] = max(dp[i-1][j],dp[i][j-1]);}}return dp[m][n];
}int main() {int n,m;cin >> n >> m;string s1,s2;//getline(cin, s1);//getline(cin, s2);cin >> s1;cin >> s2;int ret = func(s1,s2);cout << ret << endl;}