<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:
    def numDistinct(self, s: str, t: str) -> int:
        if len(t) >= len(s):
            return 1 if s == t else 0
        
        s_positions = defaultdict(list)
        for i, c in enumerate(s):
            s_positions[c].append(i)
        
        cache = {}
        def count_from(t_start, s_start):
            if t_start >= len(t):
                return 1
            if s_start >= len(s):
                return 0
            
            # if len(t) - t_start >= len(s) - s_start:
            #     return int(t[t_start:] == s[s_start:])
            
            key = (t_start, s_start)
            if key in cache:
                return cache[key]

            count = count_from(t_start, s_start + 1)
            if s[s_start] == t[t_start]:                
                count += count_from(t_start + 1, s_start + 1)
            # is_end = t_start == len(t) - 1
            # for s_pos in s_positions[t[t_start]]:
            #     if s_pos >= s_start:
            #         if is_end:
            #             count += 1
            #         else:
            #             count += count_from(t_start + 1, s_pos + 1)
            cache[key] = count
            return count
        return count_from(0, 0)
89478