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 };
  • 相关阅读:
    堆与堆排序
    利用openssl进行RSA加密解密
    [转载]编辑器圣战
    七月底的小结
    计算机是怎么样工作的?
    Linux进程地址空间之初探:一
    微软2013暑期实习笔试回忆
    微软编程之美资格赛
    微软编程之美初赛
    rootkit:实现隐藏进程
  • 原文地址:https://www.cnblogs.com/hongyang/p/6428546.html
Copyright © 2011-2022 走看看