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






  • 相关阅读:
    python学习笔记4核心类型字典
    python学习笔记5核心类型元组和文件及其他
    python学习笔记11异常总结
    python学习笔记14类总结
    python学习笔记17常用函数总结整理
    python学习笔记1核心类型数字
    python学习笔记3核心类型列表
    python学习笔记16各种模块和开放工具收集整理
    源码、反码、补码
    素数
  • 原文地址:https://www.cnblogs.com/pangblog/p/3327649.html
Copyright © 2011-2022 走看看