每日leetcode-115

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).

一个简单的动态规划即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int numDistinct(string s, string t) {
int lens = s.size(), lent = t.size();
vector<vector<int>> dp(lens + 1, vector<int>(lent + 1, 0));
for (int i = 0; i <= lens; i++) {
dp[i][0] = 1;
}
for (int i = 1; i <= lens; i++) {
for (int j = 1; j <= i && j <= lent; j++) {
dp[i][j] = (int)((long long)(s[i - 1] == t[j - 1] ? dp[i - 1][j - 1] : 0) + dp[i - 1][j]);
}
}
return dp[lens][lent];
}
};