<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 getDistSubs(int nIndex, int nSize, int nOffset, string& sBase, string& sTarget, string sCurrent, map<string, map<int,int>>&dp) {
		if (nSize == nIndex) {
			if (0 == sCurrent.compare(sTarget)) {
				return dp[sCurrent][nOffset] = 1;
			}
		}
		map<string, map<int,int>>::iterator _it = dp.find(sCurrent);
		if (dp.end() != _it) {
			map<int, int>::iterator _it1 = _it->second.find(nOffset);
			if (_it->second.end() != _it1) {
				return _it1->second;
			}
		}
		int nLength = sBase.length();
		int nCount = 0;
		for (int i = nOffset; i < nLength; i++) {
			if (sTarget[nIndex] != sBase[i]) continue;
            if (nLength - i < nSize - nOffset) continue;
			nCount += getDistSubs(nIndex + 1, nSize, i + 1, sBase, sTarget, sCurrent + sBase[i], dp);
		}
		return dp[sCurrent][nOffset] = nCount;
	}
	int numDistinct(string s, string t) {
        unordered_map<char,int> stat;
        int nSize = t.size();
        for (int i = 0; i < nSize; i++) {
            stat[t[i]]++;
        }
        nSize = s.size();
        for (int i = 0; i < nSize; i++) {
            stat[s[i]]--;
        }
        unordered_map<char,int>::iterator _it = stat.begin();
        while (_it != stat.end()) {
            if (_it->second > 0) return 0;
            _it++;
        }
		string sCurrent;
		map<string, map<int,int>> dp;
		getDistSubs(0, t.length(), 0, s, t, sCurrent, dp);
		return dp[sCurrent].begin()->second;
	}
};
243176