Given a string S and a string T, count the number of distinct subsequences of T in S.
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.
思路:
dp[i][j]表示 # of T[0...j-1] in S[0...i-1] (dp[0][0]表示s=NULL,t=NULL的情况)
如果S[i]!=T[j],那么dp[i][j]=dp[i-1][j]
如果S[i]=T[j],dp[i][j]=dp[i-1][j]+j抽出的情况=dp[i-1][j]+dp[i-1][j-1] (注意:这里并不是简单的dp[i-1][j]+1, j抽出后,dp[i-1][j-1]是要大于dp[i-1][j]的)
class Solution { public: int numDistinct(string s, string t) { int sLen = s.length(); int tLen = t.length(); vector<vector<int>> dp(sLen+1, vector<int>(tLen+1,0)); for(int i = 0; i <= sLen; i++){ //if t==NULL, 1 method to match dp[i][0]=1; } for(int i = 1; i <=sLen; i++){ for(int j = 1; j <= tLen; j++){ if(s[i-1]==t[j-1]){ dp[i][j]=dp[i-1][j]+dp[i-1][j-1]; } else{ dp[i][j]=dp[i-1][j]; } } } return dp[sLen][tLen]; } };