<p>Given two strings <code>text1</code> and <code>text2</code>, return <em>the length of their longest <strong>common subsequence</strong>. </em>If there is no <strong>common subsequence</strong>, return <code>0</code>.</p>

<p>A <strong>subsequence</strong> of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.</p>

<ul>
	<li>For example, <code>&quot;ace&quot;</code> is a subsequence of <code>&quot;abcde&quot;</code>.</li>
</ul>

<p>A <strong>common subsequence</strong> of two strings is a subsequence that is common to both strings.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> text1 = &quot;abcde&quot;, text2 = &quot;ace&quot; 
<strong>Output:</strong> 3  
<strong>Explanation:</strong> The longest common subsequence is &quot;ace&quot; and its length is 3.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> text1 = &quot;abc&quot;, text2 = &quot;abc&quot;
<strong>Output:</strong> 3
<strong>Explanation:</strong> The longest common subsequence is &quot;abc&quot; and its length is 3.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> text1 = &quot;abc&quot;, text2 = &quot;def&quot;
<strong>Output:</strong> 0
<strong>Explanation:</strong> There is no such common subsequence, so the result is 0.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= text1.length, text2.length &lt;= 1000</code></li>
	<li><code>text1</code> and <code>text2</code> consist of only lowercase English characters.</li>
</ul>

class Solution {
    int f(int i1, int i2, string &s1, string &s2, vector<vector<int>>& dp) {
        if(i1>=s1.size() || i2>=s2.size()) return 0;
        if(dp[i1][i2]!=-1){
            return dp[i1][i2];
        }
        int a=f(i1,i2+1,s1,s2,dp);
        a=max(a,f(i1+1,i2,s1,s2,dp));
        if(s1[i1]==s2[i2]) a=max(a,1+f(i1+1,i2+1,s1,s2,dp));
        return dp[i1][i2]=a;
    }

public:
    int longestCommonSubsequence(string text1, string text2) {
        int n1 = text1.size();
        int n2 = text2.size();
        if(text1==text2) return n1;
        vector<vector<int>> dp(n1 , vector<int>(n2 , -1));
        return f(0,0,text1,text2,dp);
        // for (int i = 0; i < n1; i++) {
        //     for (int j = 0; j < n2; j++) {
        //         if (text1[i] == text2[j]) {
        //             if(i>0&&j>0)dp[i][j] = 1 + dp[i-1][j-1];
        //             else dp[i][j]=1;
        //         } else {
        //             if(i>0&&j>0)dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
        //             else if(i>0) dp[i][j]=dp[i-1][j];
        //             else if(j>0) dp[i][j]=dp[i][j-1];
        //         }
        //     }
        // }

        // return dp[n1-1][n2-1];
    }
};
20239