• 【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];
        }
    };
  • 相关阅读:
    nginx内置变量
    MySQL获取错误编号 try判断 获取 Exception 上的错误
    MySQL错误代码大全(转)
    PHP递归菜单/权限目录(无限极数组)
    PHP魔术方法
    php and和&&的一个坑(文章是发现其他博客,保存自己笔记)
    nginx配置php与前后端分离(文档只供本人观看,接受错误但勿喷!)
    servlet的构造器与init方法
    模板方法设计模式
    MVC
  • 原文地址:https://www.cnblogs.com/luntai/p/5660500.html
Copyright © 2020-2023  润新知