Advertisement
Josif_tepe

Untitled

May 28th, 2024
653
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.03 KB | None | 0 0
  1. class Solution {
  2. public:
  3. string a, b;
  4. int dp[1005][1005];
  5. const int INF = 2e8;
  6. int rec(int i, int j) {
  7.     if(i == -1) {
  8.         return 0;
  9.     }
  10.     if(j == -1) {
  11.         return 0;
  12.     }
  13.     if(dp[i][j] != -1) {
  14.         return dp[i][j];
  15.     }
  16.     int res = -INF;
  17.     if(a[i] == b[j]) {
  18.         res = max(res, rec(i - 1, j - 1) + 1);
  19.     }
  20.     res = max(res, rec(i - 1, j));
  21.     res = max(res, rec(i, j - 1));
  22.     return dp[i][j] = res;
  23. }
  24.     int longestCommonSubsequence(string text1, string text2) {
  25.         a = text1;
  26.         b = text2;
  27.     vector<vector<int>> dp(a.size() + 1, vector<int>(b.size() + 1, 0));
  28.     int res = 0;
  29.     for(int i = 1; i <= a.size(); i++) {
  30.         for(int j = 1; j <= b.size(); j++) {
  31.             if(a[i - 1] == b[j - 1]) {
  32.                 dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 1);
  33.             }
  34.             dp[i][j] = max(dp[i][j], dp[i - 1][j]);
  35.             dp[i][j] = max(dp[i][j], dp[i][j - 1]);
  36.             res = max(res, dp[i][j]);
  37.         }
  38.     }
  39.     return res;
  40.     }
  41. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement