Advertisement
Oppenheimer

longest common subsequence

Aug 14th, 2022 (edited)
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. // longest common subsequence
  2. // [1 ,2 ,3, 4]
  3. // subsequnce (order matters but maybe not continuous)
  4. // substring or subarray .. (need to be contigous)
  5. // subset same as subsequence ..
  6. int solve(string s1 , string s2){
  7.     int sa = s1.length();
  8.     int sb = s2.length();
  9.     vector<vector<int>> dp (sa+1 ,vector<int>(sb+1,0));
  10.     // a represents the ath element .. b represents the knapsack present
  11.    
  12.     for(int a=1;a<=sa;a++){
  13.         for(int b=1;b<=sb;b++){
  14.             if(s1[a-1] == s2[b-1]){
  15.             dp[a][b] = 1 + dp[a-1][b-1]; //here we can choose ith element again
  16.             }else{
  17.             dp[a][b] = max(dp[a-1][b] , dp[a][b-1]); // cant choose the ath element becuase its weight is more
  18.             }
  19.         }
  20.     }
  21.    
  22.     // to print the lcs
  23.     int i = sa;
  24.     int j = sb;
  25.     string res = "";
  26.     while(i>0 && j>0){
  27.         if(s1[i-1] == s2[j-1] ){
  28.             res+=s1[i-1];
  29.             i--;
  30.             j--;
  31.         }else{
  32.          if(dp[i-1][j] > dp[i][j-1])i--;
  33.             else j--;
  34.        
  35.         }
  36.     }
  37.    
  38.     reverse(res.begin(),res.end()); /////// reversing the string is very important
  39.     cout << res <<"\n";
  40.     return dp[sa][sb]; // gives to length of lcs
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement