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

    思路:

    经典的DP问题,用result[i][j]表示长度为i的S转换到长度为j的T的结果数。

    s[i-1]==t[j-1]的时候result[i][j]=result[i-1][j-1]+result[i-1][j];

    s[i-1]!=t[j-1]的时候result[i][j]=result[i-1][j];

    Acceped Code:

     1 class Solution {
     2 public:
     3     int numDistinct(string s, string t) {
     4         if(s.empty()||t.empty())
     5         return 0;
     6         if(s.length()<t.length())
     7         return 0;
     8         int len1=s.length();
     9         int len2=t.length();
    10         vector<vector<int>> result(len1+1,vector<int>(len2+1,0));
    11         for(int i=0;i<=len1;i++)
    12         result[i][0]=1;
    13         for(int i=1;i<=len1;i++)
    14         for(int j=1;j<=len2;j++)
    15         {
    16             result[i][j]=result[i-1][j];
    17             if(s[i-1]==t[j-1])
    18             result[i][j]+=result[i-1][j-1];
    19         }
    20         return result[len1][len2];
    21     }
    22 };
  • 相关阅读:
    Ansible运维自动化(配置管理工具)
    Haproxy 概述及搭建
    Hadoop 单机与完全分布式配置
    大数据与Hadoop
    Hadoop 高可用
    kafka原理和集群
    zookeeper原理及搭建
    个人记录点滴
    Java中导入Excel文件
    反射相关
  • 原文地址:https://www.cnblogs.com/hongyang/p/6428546.html
Copyright © 2011-2022 走看看