zoukankan      html  css  js  c++  java
  • leetcode_question_115 Distinct Subsequences

    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.

    Recurse:
    Judge Small: Accepted!
    Judge Large: Time Limit Exceeded

     

    int numDistinct(string S, string T) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            int slen = S.length();
            int tlen = T.length();
            if(slen <= tlen){
                if(S == T) return 1;
                else return 0;
            }
            
            if(S[slen-1] != T[tlen-1]) return numDistinct(S.substr(0,slen-1), T);
            else
                return numDistinct(S.substr(0,slen-1), T) + numDistinct(S.substr(0,slen-1), T.substr(0,tlen-1));
        }

    dp:
    Judge Small: Accepted!
    Judge Large: Accepted!

    int numDistinct(string S, string T) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            int col = S.length() + 1;
            int row = T.length() + 1;
            int** dp = new int*[row];
            for(int i = 0; i < row; ++i)
                dp[i] = new int[col];
            
            for(int i = 0; i < row; ++i)
                dp[i][0] = 0;
            for(int j = 0; j < col; ++j)
                dp[0][j] = 1;
            
            for(int i = 1; i < row; ++i)
                for(int j = 1; j < col; ++j)
                    if(T[i-1] == S[j-1]) dp[i][j] = dp[i-1][j-1] + dp[i][j-1];
                    else dp[i][j] = dp[i][j-1];
                    
            int tmp = dp[row-1][col-1];
            
            for(int i = 0; i < row; ++i)
                delete[] dp[i];
            delete[] dp;
            
            return tmp;
        }






  • 相关阅读:
    【笔记】Hierarchical Attention Networks for Document Classification
    Chart Parser 中 Earley's 算法的应用
    使用 JFlex 生成词法分析器的安装配置及简单示例
    UNIX 系统下退出 git commit 编辑器
    SQL语法
    MySQL 和 Javaweb 的报错合集
    最短路径(SP)问题相关算法与模板
    dfs | Security Badges
    redis哨兵机制图谱
    docker笔记
  • 原文地址:https://www.cnblogs.com/pangblog/p/3327649.html
Copyright © 2011-2022 走看看