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






  • 相关阅读:
    机器学习中的距离度量
    ubuntu 安装JDK
    pandas 代码
    pandas 常用统计方法
    python内置函数map/reduce/filter
    详解SQL Server连接(内连接、外连接、交叉连接)
    什么是SAD,SAE,SATD,SSD,SSE,MAD,MAE,MSD,MSE?
    数据挖掘算法源代码:很好的参考资料
    python linecache模块读取文件用法详解
    python读取文件指定行
  • 原文地址:https://www.cnblogs.com/pangblog/p/3327649.html
Copyright © 2011-2022 走看看