# 115.Distinct Subsequences

## 刷题内容

• https://leetcode.com/problems/distinct-subsequences/

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

Example 1:

Input: S = "rabbbit", T = "rabbit"
Output: 3
Explanation:

As shown below, there are 3 ways you can generate "rabbit" from S.
(The caret symbol ^ means the chosen letters)

rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^
Example 2:

Input: S = "babgbag", T = "bag"
Output: 5
Explanation:

As shown below, there are 5 ways you can generate "bag" from S.
(The caret symbol ^ means the chosen letters)

babgbag
^^ ^
babgbag
^^    ^
babgbag
^    ^^
babgbag
^  ^^
babgbag
^^^


˼· **- ʱ�临�Ӷ�: O(n^2)*- �ռ临�Ӷ�: O(n^2)***

������һ����̬�滮�����⣬��̬����Ĺؼ��ľ���д��״̬ת�Ʒ��̡内容描述Ƕ���һ������ dp[m][n],��ʾ�� s[m] �� t[n] ֮ǰ�м���ƥ内容描述У内容描述ǿ���д��״̬ת�Ʒ��� �� s[m] != t[n]��dp[m][n] = dp[m - 1][n]��else dp[m][n] += (dp[m - 1][n] + dp[m - 1][n - 1])

class Solution {
public:
int numDistinct(string s, string t) {
int l1 = s.length(),l2 = t.length();
int dp[l1 + 1][l2 + 1];
memset(dp,0,sizeof(dp));
for(int i = 1;i <= l1;++i)
if(s[i - 1] == t[0])
dp[i][1] = 1;
for(int i = 1;i <= l1;++i)
for(int j = 1;j <= l2;++j)
{
if(s[i - 1] != t[j - 1])
dp[i][j] = dp[i - 1][j];
else
dp[i][j] += (dp[i - 1][j - 1] + dp[i - 1][j]);
//cout << dp[i][j] << " ";
}
return dp[l1][l2];
}
};


apachecn/AiLearning