码迷,mamicode.com
首页 > Web开发 > 详细

115. Distinct Subsequences(js)

时间:2019-04-24 23:23:54      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:mdi   ons   pre   bbb   cte   bing   main   bin   har   

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];
};

 



115. Distinct Subsequences(js)

标签:mdi   ons   pre   bbb   cte   bing   main   bin   har   

原文地址:https://www.cnblogs.com/xingguozhiming/p/10765676.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!