Given a string S and a string T, count the number of distinct subsequences of S which equals T.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE"
is a subsequence of "ABCDE"
while "AEC"
is not).
Here is an example:
S = "rabbbit"
, T = "rabbit"
Return 3
.
class Solution {
public:
int numDistinct(string s, string t) {
vector<vector<int>> dp(t.size() + 1, vector<int>(s.size() + 1, 0));
for(int i = 0; i <= s.size(); i++)
dp[0][i] = 1;
for(int i = 1; i <= t.size(); i++) {
for(int j = 1; j <= s.size(); j++) {
if(t[i-1] == s[j-1])
dp[i][j] = dp[i-1][j-1] + dp[i][j-1];
else
dp[i][j] = dp[i][j-1];
}
}
return dp[t.size()][s.size()];
}
};
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有