class Solution {
public:
    /**
     * longest common subsequence
     * @param s1 string字符串 the string
     * @param s2 string字符串 the string
     * @return string字符串
     */
    /*
    dp(i,j)表示以s1(i),s2(j)最长公共子序列
    开始倒推,
    if(dp(i,j) = maxLen,--, && s1(i) == s2(j)) {
        push back.
    }
    */
    string LCS(string s1, string s2) {
        // write code here
        int len1 = s1.size(), len2 = s2.size();
        if (len1 == 0 || len2 == 0) {
            return "-1";
        }
        int maxLen = 0;
        vector<vector<int>>dp(len1 + 1, vector<int>(len2 + 1, 0));
        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                if (s1[i-1] == s2[j-1]) {
                    dp[i][j] = dp[i-1][j-1] + 1;
                } else {
                    dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
                }
                 maxLen = max(maxLen, dp[i][j]);
            }
            
            
        }
        
        if (maxLen == 0) {
            return "-1";
        }
        // 逆推
        string ret;
        for (int i = len1; i >=0; i--) {
            for (int j = len2; j >= 0; j--) {
                if (dp[i][j] == maxLen && s1[i-1] == s2[j-1]) {
                    maxLen--;
                    ret += s1[i-1];
                } 
            }
        }
       
        for (int i = len1, j = len2; dp[i][j] >= 1;) {
            if(s1[i-1] == s2[j-1]) {
                ret += s1[i-1];
                i--;j--;
            } else if (dp[i-1][j] > dp[i][j-1]) {
                i--;
            } else {
                j--;
            }
        }
        reverse(ret.begin(), ret.end());
        return ret;
    }
};