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];
        }
    };
  • 相关阅读:
    jquery实现记住用户名和密码
    从mysql8.0.15升级到8.0.16
    mysql8.0.15二进制安装
    DML、DDL、DCL的分别是什么
    redis3.2.10单实例安装测试
    redis5.0.3单实例简单安装记录
    percona-xtrabackup快速安装及其简单使用
    pt-show-grants的用法
    Centos6安装Percona-tools工具
    sshpass-Linux命令之非交互SSH密码验证
  • 原文地址:https://www.cnblogs.com/luntai/p/5660500.html
Copyright © 2011-2022 走看看