Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- string a, b;
- int dp[1005][1005];
- const int INF = 2e8;
- int rec(int i, int j) {
- if(i == -1) {
- return 0;
- }
- if(j == -1) {
- return 0;
- }
- if(dp[i][j] != -1) {
- return dp[i][j];
- }
- int res = -INF;
- if(a[i] == b[j]) {
- res = max(res, rec(i - 1, j - 1) + 1);
- }
- res = max(res, rec(i - 1, j));
- res = max(res, rec(i, j - 1));
- return dp[i][j] = res;
- }
- int longestCommonSubsequence(string text1, string text2) {
- a = text1;
- b = text2;
- vector<vector<int>> dp(a.size() + 1, vector<int>(b.size() + 1, 0));
- int res = 0;
- for(int i = 1; i <= a.size(); i++) {
- for(int j = 1; j <= b.size(); j++) {
- if(a[i - 1] == b[j - 1]) {
- dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 1);
- }
- dp[i][j] = max(dp[i][j], dp[i - 1][j]);
- dp[i][j] = max(dp[i][j], dp[i][j - 1]);
- res = max(res, dp[i][j]);
- }
- }
- return res;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement