zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    接受了Edit Distance的教训,该用了vector<vector<int> >勉强过了大数据。f[i][j]表示S[i]和T[j]相同的情况下,产生的情况个数。

    最后sum(f[i][T.size()]), 0<= i <= S.size(),就是结果了。

     1 class Solution {
     2 public:
     3     int numDistinct(string S, string T) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         vector<vector<int> > f(S.size()+1, vector<int>(T.size()+1));
     7         
     8         f[0][0] = 1;
     9         for(int i = 1; i <= S.size(); i++)
    10             f[i][0] = 0;
    11             
    12         for(int i = 1; i <= T.size(); i++)
    13             f[0][i] = 0;
    14             
    15         for(int i = 1; i <= S.size(); i++)
    16             for(int j = 1; j <= T.size(); j++)
    17                 if (S[i-1] == T[j-1])
    18                 {
    19                     f[i][j] = 0;
    20                     for(int k = 0; k < i; k++)
    21                         f[i][j] += f[k][j-1];
    22                 }
    23                 else
    24                     f[i][j] = 0;
    25         
    26         int sum = 0;
    27         for(int i = 0; i <= S.size(); i++)
    28             sum += f[i][T.size()];
    29             
    30         return sum;
    31     }
    32 };
  • 相关阅读:
    Vue 项目结构介绍
    使用命令行创建 Vue 项目
    GitHub无法访问怎么办?-- 已解决
    Spa 单页面应用简介
    JetBrains WebStorm 常用快捷键总结
    使用 WebStorm + Vue 写一个九九乘法表
    使用 WebStorm 2018 运行第一个 Vue 程序
    小工具
    elasticsearch安装部署
    命令行连接ftp
  • 原文地址:https://www.cnblogs.com/chkkch/p/2757687.html
Copyright © 2011-2022 走看看