115. Distinct Subsequences(js)
115. 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
^^^
题意:在S找出所有包含T的子序列,输出个数
代码如下:
/** * @param {string} s * @param {string} t * @return {number} */ var numDistinct = function(s, t) { let dp=[]; for(let i=0;i<t.length+1;i++){ dp[i]=[]; for(let j=0;j<s.length+1;j++){ if(i==0) dp[i][j]=1; else dp[i][j]=0; } } for(let i=0;i<t.length;i++){ for(let j=0;j<s.length;j++){ if(t[i]===s[j]){ dp[i+1][j+1]=dp[i][j]+dp[i+1][j]; }else{ dp[i+1][j+1]=dp[i+1][j]; } } } return dp[t.length][s.length]; };