• 115. Distinct Subsequences (String; DP)


    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];
        }
    };
  • 相关阅读:
    网络流,再出发!
    2SAT
    并查集
    最大密度子图
    网络流提高专题(洛谷题单)
    JQuery 操作 ListBox间移动和ListBox内移动
    关于多表Update和Delete的应用
    XML格式与DataTable、DataSet、DataView格式的转换
    FCKeditor配置和精简
    点击fileupload后button事件不起作用
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4922290.html
Copyright © 2020-2023  润新知