# 115.distinct-subsequences

## Statement

• Difficulty: Hard
• Tag: `字符串` `动态规划`

``````输入：s = "rabbbit", t = "rabbit"

rabbbit
rabbbit
rabbbit``````

``````输入：s = "babgbag", t = "bag"

babgbag
babgbag
babgbag
babgbag
babgbag
``````

• `0 <= s.length, t.length <= 1000`
• `s``t` 由英文字母组成

• Difficulty: Hard
• Tag: `String` `Dynamic Programming`

Given two strings `s` and `t`, return the number of distinct subsequences of `s` which equals `t`.

A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., `"ACE"` is a subsequence of `"ABCDE"` while `"AEC"` is not).

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

Example 1:

``````Input: s = "rabbbit", t = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from S.
rabbbit
rabbbit
rabbbit
``````

Example 2:

``````Input: s = "babgbag", t = "bag"
Output: 5
Explanation:
As shown below, there are 5 ways you can generate "bag" from S.
babgbag
babgbag
babgbag
babgbag
babgbag``````

Constraints:

• `1 <= s.length, t.length <= 1000`
• `s` and `t` consist of English letters.

## Solution

``````#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

#define endl "\n"
#define fi first
#define se second
#define all(x) begin(x), end(x)
#define rall rbegin(a), rend(a)
#define bitcnt(x) (__builtin_popcountll(x))
#define complete_unique(a) a.erase(unique(begin(a), end(a)), end(a))
#define mst(x, a) memset(x, a, sizeof(x))
#define MP make_pair

using ll = long long;
using ull = unsigned long long;
using db = double;
using ld = long double;
using VLL = std::vector<ll>;
using VI = std::vector<int>;
using PII = std::pair<int, int>;
using PLL = std::pair<ll, ll>;

using namespace __gnu_pbds;
using namespace std;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
const ll mod = 1e9 + 7;

template <typename T, typename S>
inline bool chmax(T &a, const S &b) {
return a < b ? a = b, 1 : 0;
}

template <typename T, typename S>
inline bool chmin(T &a, const S &b) {
return a > b ? a = b, 1 : 0;
}

#ifdef LOCAL
#include <debug.hpp>
#else
#define dbg(...)
#endif

class Solution {
public:
int numDistinct(string s, string t) {
int n = s.length();
int m = t.length();
auto f = vector<ll>(m + 1, 0);

int Max = 2e9;

f[0] = 1;
for (const auto &c : s) {
for (int i = m; i >= 1; i--) {
char tt = t[i - 1];
if (tt != c) {
continue;
}

f[i] += f[i - 1];
if (f[i] > Max) {
f[i] = 0;
}
}
}

return f[m];
}
};

#ifdef LOCAL

int main() {
return 0;
}

#endif
``````