115. Distinct Subsequences
Hard NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- 2-D Dynamic Programming
- Time
- O(M*N)
- Space
- O(M)
Standard Solution (C++)
SummaryGiven a source string `s` and a target string `t`, count the number of distinct ways to delete characters from `s` (preserving relative order) such that the remaining characters spell out `t` exactly.
Approach
- Define
dp[i][j]as the number of distinct subsequences ofs[0..i-1]that equalt[0..j-1]. - Base cases:
dp[i][0] = 1for alli(empty target can always be matched), anddp[0][j] = 0forj > 0(non-empty target cannot be matched from an empty source). - Transition: if
s[i-1] == t[j-1], we can either use that character (dp[i-1][j-1]) or skip it (dp[i-1][j]); otherwise we must skip it (dp[i][j] = dp[i-1][j]). - Space is optimized to O(n) by processing the
dprow in reverse, avoiding overwriting values still needed for the current row.
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
int numDistinct(string s, string t) {
int m = s.size(), n = t.size();
// dp[j] = number of ways to form t[0..j-1] using s characters seen so far.
// Use long long internally to avoid overflow before clamping to int.
vector<long long> dp(n + 1, 0);
dp[0] = 1; // empty target is always matched exactly one way
// Iterate over each character of s
for (int i = 0; i < m; ++i) {
// Traverse t right-to-left so we read dp[j-1] from the previous row
for (int j = n; j >= 1; --j) {
if (s[i] == t[j - 1]) {
dp[j] += dp[j - 1];
}
}
}
return static_cast<int>(dp[n]);
}
};
Time O(m * n) Space O(n)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
public:
int numDistinct(string s, string t) {
int len1=s.length();
int len2=t.length();
if(len1<len2){
return 0;
}
vector<int> dp(len1, 0); // dp[i] means the num of subsequence ending with s[i]
vector<long long> prefixSum(len1, 0); // prefixSum means the accumulated num ending with s[i]
// init
if(s[0]==t[0]){
prefixSum[0]=1;
}
for(int i=1; i<len1; ++i){
if(s[i]==t[0]){
prefixSum[i]+=1;
}
prefixSum[i]+=prefixSum[i-1];
}
for(int j=1; j<len2; ++j){
for(int i=j; i<len1; ++i){
if(s[i]==t[j]){
dp[i]=prefixSum[i-1];
}
else{
dp[i]=0;
}
}
prefixSum[j-1]=0;
for(int i=j; i<len1; ++i){
prefixSum[i]=dp[i]+prefixSum[i-1];
}
}
return prefixSum[len1-1];
}
};
// Time Complexity: O(M*N)
// Space Complexity: O(M), M is the length of s. Time O(M*N) Space O(M)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.