
Sponsored
Sponsored
We use a 2D DP table where `dp[i][j]` represents the number of distinct subsequences of `s[0..i-1]` which forms `t[0..j-1]`. The size of the table is `(m+1)x(n+1)` where `m` is the length of `s` and `n` is the length of `t`.
Initialize `dp[0][0]` to 1 because an empty string is a subsequence of itself, and `dp[i][0]` to 1 for all `i`, because an empty `t` is a subsequence of any prefix of `s`. Then, for each character `s[i-1]` and `t[j-1]`, update the DP table as follows:
Time Complexity: O(m * n), where `m` is the length of `s` and `n` is the length of `t`.
Space Complexity: O(m * n) for the DP table.
1#include <vector>
2#include <string>
3
4int numDistinct(std::string s, std::string t) {
5 int m = s.size();
6 int n = t.size();
7 std::vector<std::vector<long long>> dp(m + 1, std::vector<long long>(n + 1, 0));
8
9 for (int i = 0; i <= m; ++i) {
10 dp[i][0] = 1;
11 }
12
13 for (int i = 1; i <= m; ++i) {
14 for (int j = 1; j <= n; ++j) {
if (s[i - 1] == t[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[m][n];
}
int main() {
std::string s = "rabbbit";
std::string t = "rabbit";
std::cout << numDistinct(s, t) << std::endl;
return 0;
}This C++ code similarly uses a nested vector `dp` to store the number of subsequences. It initializes `dp[i][0]` to 1 since an empty `t` can be formed from any prefix of `s` and updates the table through nested loops. We return the value at `dp[m][n]`, which contains the final result.
We can optimize the space complexity by observing that to calculate `dp[i][j]`, we only need values from the previous row. Thus, we can use a 2-row approach, maintaining only `previous` and `current` arrays to save space. This reduces the space complexity to O(n), where `n` is the length of `t`.
The transition is similar to the 2D approach but only updates the necessary parts of the `current` array based on the `previous` row.
Time Complexity: O(m * n), where `m` is the length of `s` and `n` is the length of `t`.
Space Complexity: O(n), using only two rows for DP storage.
This JavaScript approach uses two 1D arrays `prev` and `cur`. The main logic involves updating only necessary states per iteration, switching arrays at each outer loop step to retain recent results efficiently.