<p>Given two strings s and t, return <i>the number of distinct</i> <b><i>subsequences</i></b><i> of </i>s<i> which equals </i>t.</p>

<p>The test cases are generated so that the answer fits on a 32-bit signed integer.</p>

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

<pre>
<strong>Input:</strong> s = &quot;rabbbit&quot;, t = &quot;rabbit&quot;
<strong>Output:</strong> 3
<strong>Explanation:</strong>
As shown below, there are 3 ways you can generate &quot;rabbit&quot; from s.
<code><strong><u>rabb</u></strong>b<strong><u>it</u></strong></code>
<code><strong><u>ra</u></strong>b<strong><u>bbit</u></strong></code>
<code><strong><u>rab</u></strong>b<strong><u>bit</u></strong></code>
</pre>

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

<pre>
<strong>Input:</strong> s = &quot;babgbag&quot;, t = &quot;bag&quot;
<strong>Output:</strong> 5
<strong>Explanation:</strong>
As shown below, there are 5 ways you can generate &quot;bag&quot; from s.
<code><strong><u>ba</u></strong>b<u><strong>g</strong></u>bag</code>
<code><strong><u>ba</u></strong>bgba<strong><u>g</u></strong></code>
<code><u><strong>b</strong></u>abgb<strong><u>ag</u></strong></code>
<code>ba<u><strong>b</strong></u>gb<u><strong>ag</strong></u></code>
<code>babg<strong><u>bag</u></strong></code></pre>

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

<ul>
	<li><code>1 &lt;= s.length, t.length &lt;= 1000</code></li>
	<li><code>s</code> and <code>t</code> consist of English letters.</li>
</ul>

class Solution {
public:

    void lcs(string s, string t, vector<vector<int>> &dp){
        int n=s.size(), m=t.size();
        int count=0;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                int take = 0;
                if(s[i-1]==t[j-1]){
                    take = dp[i-1][j-1] + 1;
                }
                int notTake = max(dp[i-1][j], dp[i][j-1]);
                if(s[i-1]==t[j-1] && take==notTake) count++;
                dp[i][j] = max(take, notTake);
            }
        }        
    }

    int dfs(int itr1, int itr2, string s, string t, vector<vector<int>> &dp, int size, vector<vector<int>> &dp2){
        if(size!=dp[itr1][itr2])
            return 0;
        
        if(itr1==0 || itr2==0){
            if(size==0)
                return 1;
            return 0;
        }

        if(dp2[itr1][itr2]!=-1)
            return dp2[itr1][itr2];

        int take = 0;
        if(s[itr1-1]==t[itr2-1])
            take = dfs(itr1-1, itr2-1, s, t, dp, size-1, dp2);

        int notTake = dfs(itr1-1, itr2, s, t, dp, size, dp2) + 
            dfs(itr1, itr2-1, s, t, dp, size, dp2); 

        return dp2[itr1][itr2] = take + notTake;
    }
    int numDistinct(string s, string t) {
        int n=s.size(), m=t.size();
        vector<vector<int>> dp(n+1, vector<int>(m+1, 0));
        vector<vector<int>> dp2(n+1, vector<int>(m+1, -1));
        lcs(s, t, dp);
        return dfs(n, m, s, t, dp, m, dp2);
    }
};
61963