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.

      该题解析参考自LeetCode题解

      设状态为dp[i][j],表示T[0, j]在S[0, i]里出现的次数。首先,无论S[i]和T[j]是否相等,若不使用S[i],则dp[i][j]=dp[i-1][j];若S[i]=T[j],则可以使用S[i],此时dp[i][j]=dp[i-1][j]+dp[i-1][j-1]。

      代码如下:

     1 class Solution {
     2 public:
     3     int numDistinct(string s, string t) {
     4         int szS = s.size();
     5         int szT = t.size();
     6         if(szS < szT)
     7             return 0;
     8         
     9         vector<vector<int> > dp(szS + 1, vector<int>(szT + 1, 0));
    10         for(int i = 0; i < szS + 1; i++)
    11             dp[i][0] = 1;
    12         
    13         for(int i = 1; i < szS + 1; i++)
    14             for(int j = 1; j < szT + 1; j++)
    15             {
    16                 if(s[i-1] != t[j-1])
    17                     dp[i][j] = dp[i-1][j];
    18                 else
    19                     dp[i][j] = dp[i-1][j] + dp[i-1][j-1];
    20             }
    21 
    22         return dp[szS][szT];
    23     }
    24 };

       

  • 相关阅读:
    ubuntu16.04编译安装PHP7.0.9,Nginx1.10,Phalcon3.1扩展
    阿里云云大使推广产品集合
    mysql性能优化-慢查询分析、优化索引和配置
    Js学习笔记(二)
    Javascript学习笔记(一)
    HashMap
    JDK 1.8 新特性
    Java转型
    Java IO
    Java正则表达式
  • 原文地址:https://www.cnblogs.com/xiehongfeng100/p/4581325.html
Copyright © 2011-2022 走看看