<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:
    int numDistinct(string s, string t) {
        if(s.size()<t.size())return 0;
        vector<vector<int>> mem(s.size(),vector<int>(t.size(),-1));
        return solve(s,t,0,0,mem);
    }
    int solve(string s, string t, int s_begin, int t_begin, vector<vector<int>>& mem){
        // if(mem[s_begin][t_begin]!=-1)return mem[s_begin][t_begin];
        if(s.size()-s_begin<t.size()-t_begin){
            mem[s_begin][t_begin]=0;
            return 0;
        }
        int count=0;
        if(t.size()-t_begin==1){
            for(int k=s_begin;k<s.size();k++){
                if(mem[k][t_begin]!=-1){
                    count+=mem[k][t_begin];
                    break;
                }
                if(s[k]==t[t_begin])count++;
            }
            mem[s_begin][t_begin]=count;
        }
        else{
            for(int i=s_begin;i<s.size()-1;i++){
                if(s[i]==t[t_begin]){
                    if(mem[i][t_begin]==-1)mem[i][t_begin]=solve(s,t,i+1,t_begin+1,mem);
                    count+=mem[i][t_begin];
                }
                else{
                    if(mem[i][t_begin]==-1)mem[i][t_begin]=solve(s,t,i+1,t_begin,mem);
                }
            }
        }
        return count;
    }
};
362258