1143. Longest Common Subsequence

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/tina_tian1/article/details/99773965

Given two strings text1 and text2, return the length of their longest common subsequence.

https://leetcode.com/problems/longest-common-subsequence/

Solution:

class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        
        vector<vector<int>> v(text1.size(), vector<int>(text2.size(), -1));
        
        return dp(text1,  0,  text1.size()-1,  text2,  0,  text2.size()-1, v);
    }
    
    int dp(string &text1, int s1, int e1, string &text2, int s2, int e2, vector<vector<int>> &v){
        if(s1>e1) return 0;
        if(s2>e2) return 0;
        
        if(v[e1][e2] != -1) return v[e1][e2];
        
        if(text1[e1] == text2[e2]){
             v[e1][e2] = 1 + dp(text1,  s1,  e1-1,  text2,  s2,  e2-1, v);
            return v[e1][e2] ;
        }
         v[e1][e2] = max(dp(text1,  s1,  e1-1,  text2,  s2,  e2, v), dp(text1,  s1,  e1,  text2,  s2,  e2-1, v));
        return  v[e1][e2];;
    }
};
class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        
        vector<vector<int>> v(text1.size()+1, vector<int>(text2.size()+1, 0));
        
        for(int i=1; i<=text1.size(); i++){
            for(int j=1; j<=text2.size(); j++){
                if(text2[j-1] == text1[i-1]) v[i][j] = 1 + v[i-1][j-1];
                else v[i][j] = max(v[i][j-1], v[i-1][j]);
            }
        }
        
        return v[text1.size()][text2.size()];

    }

};

猜你喜欢

转载自blog.csdn.net/tina_tian1/article/details/99773965