Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- class Solution {
- public:
- int f(int i1,int i2,string text1,string text2,vector<vector<int>> &dp) {
- if(i1==0 or i2==0) return 0;
- if(dp[i1][i2]!=-1) return dp[i1][i2];
- if(text1[i1-1]==text2[i2-1]) return dp[i1][i2]= 1 + f(i1-1,i2-1,text1,text2,dp);
- return dp[i1][i2]= max(f(i1-1,i2,text1,text2,dp),f(i1,i2-1,text1,text2,dp));
- }
- int longestCommonSubsequence(string text1, string text2) {
- vector<vector<int>> dp(text1.length()+2,vector<int>(text2.length()+2,-1));
- int n = text1.length();
- int m = text2.length();
- for(int i=0;i<=n;i++) dp[i][0]=0;
- for(int i=0;i<=m;i++) dp[0][i]=0;
- for(int i=1;i<=n;i++) {
- for(int j=1;j<=m;j++) {
- if(text1[i-1]==text2[j-1]) { dp[i][j] = 1 + dp[i-1][j-1];
- }
- else {
- dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
- }
- }
- }
- return dp[n][m];
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement