https://leetcode-cn.com/problems/distinct-subsequences/
思路:
d
p
i
j
dp_{ij}
dpij表示
s
[
i
:
]
s[i:]
s[i:]的子序列中
t
[
j
:
]
t[j:]
t[j:]出现的次数,那么初始时
d
p
[
i
]
[
m
]
=
1
dp[i][m]=1
dp[i][m]=1,当
s
[
i
]
=
t
[
j
]
s[i]=t[j]
s[i]=t[j]时,
t
[
j
]
t[j]
t[j]可以选择是否与
s
[
i
]
s[i]
s[i]匹配,从而得到
d
p
[
i
]
[
j
]
=
d
p
[
i
+
1
]
[
j
+
1
]
+
d
p
[
i
+
1
]
[
j
]
dp[i][j]=dp[i+1][j+1]+dp[i+1][j]
dp[i][j]=dp[i+1][j+1]+dp[i+1][j];否则
d
p
[
i
]
[
j
]
=
d
p
[
i
+
1
]
[
j
]
dp[i][j]=dp[i+1][j]
dp[i][j]=dp[i+1][j]。要开longlong。
class Solution {
public:
int numDistinct(string s, string t) {
int n=s.size(),m=t.size();
if(n<m)
return 0;
using ll=long long;
vector<vector<ll>> dp(n+1,vector<ll>(m+1));
for(int i=0;i<=n;i++)
dp[i][m]=1;
for(int i=n-1;i>=0;i--)
{
int minj=max(0,m-(n-i));
for(int j=m-1;j>=minj;j--)
{
dp[i][j]=dp[i+1][j];
if(s[i]==t[j])
dp[i][j]+=dp[i+1][j+1];
}
}
return dp[0][0];
}
};