zoukankan      html  css  js  c++  java
  • 【Leetcode】115. Distinct Subsequences

    Description:

      Given two string S and T, you need to count the number of T's subsequences appeared in S. The fucking problem description is so confusing.

    Input:

       String s and t

    output:

      The number

    Analysis:

      It's a dynamic processing problem. I drew the dynamic processing of counting the seq numbers and then got the correct formula by guessing? :) Most times I work out the final formula by deducing! Then i back to think it's real sense in the problem.

         dp[i][j] represents the number of subsequences in string T (ending before index i)  are appeared in string S (ending before index j). So, dp can be processed by the follow formula:

          = dp[i][j-1] + dp[i-1][j-1]     if s[j] == t[i]

     dp[i][j] 

                     = dp[i][j-1]                          if s[j] != t[i]

    BYT:

      The fucking input size of test cases in serve are ambiguity! So if you create a 2-dimension array in defined size, you will be in trouble. Dynamic structures like vector will be better!

    Code:

    class Solution {
    public:
        int numDistinct(string s, string t) {
            if(s.length() == 0 || t.length() == 0) return 0;
            //int dp[50][10908];
            vector<vector<int>> dp(t.length() + 1, vector<int>(s.length() + 1, 0));
            dp[0][0] = (t[0] == s[0])?1:0;
            for(int i = 1; i < s.length(); i ++){
                if(s[i] == t[0]) dp[0][i] = dp[0][i - 1] + 1;
                else dp[0][i] = dp[0][i - 1];
            }
            for(int i = 1; i < t.length(); i ++){
                dp[i][i - 1] = 0;
                for(int j = i; j < s.length(); j ++){
                    dp[i][j] = (t[i] == s[j])? (dp[i][j - 1] + dp[i - 1][j - 1]):dp[i][j - 1];
                }
            }
            return dp[t.length() - 1][s.length() - 1];
        }
    };
  • 相关阅读:
    数据结构:树[data struct: tree]
    关于计算机学科的一些期刊和会议(转)
    这个世界究竟是怎么了
    [思考]怎么在C#中加入新功能
    vsta相关
    Practical numerical methods with C#
    C# (CSharp)中的foreach,for关键词
    代码生成相关
    没有可用于当前位置的源代码 解决办法
    access数据库删除两个日期之间 的数据 SQL语句
  • 原文地址:https://www.cnblogs.com/luntai/p/5660500.html
Copyright © 2011-2022 走看看