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.

    动态规划!

     1 class Solution {
     2 public:
     3     int numDistinct(string S, string T) {
     4         vector<vector<int> > a(T.length() + 1, vector<int>(S.length() + 1));
     5         for (int j = 0; j <= S.length(); ++j) {
     6             a[0][j] = 0;
     7         }
     8         for (int i = 0; i <= T.length(); ++i) {
     9             a[i][0] = 0; 
    10         }
    11         for (int i = 1; i <= S.length(); ++i) {
    12             if (S[i-1] == T[0]) {
    13                 a[1][i] = a[1][i-1] + 1;
    14             } else {
    15                 a[1][i] = a[1][i-1];
    16             }
    17         }
    18         for (int i = 2; i <= T.length(); ++i) {
    19             for (int j = 1; j <= S.length(); ++j) {
    20                 if (T[i-1] == S[j-1]) {
    21                     a[i][j] = a[i-1][j-1] + a[i][j-1];
    22                 } else {
    23                     a[i][j] = a[i][j-1]; 
    24                 }
    25             }
    26         }
    27         return a[T.length()][S.length()];
    28     }
    29 };

    其实最开始的想法是dfs,果段超时。比起动规来还是递归好写一点,动规还不太熟练,得加油啊。

     1 class Solution {
     2 public:
     3     void dfs(string &S, int idxs, string &T, int idxt, int &res) {
     4         if (idxt == T.length()) {
     5             ++res;
     6             return;
     7         }
     8         if (idxs == S.length()) {
     9             return;
    10         }
    11         if (S[idxs] == T[idxt]) {
    12             dfs(S, idxs + 1, T, idxt + 1, res);
    13         } 
    14         dfs(S, idxs + 1, T, idxt, res);
    15     }
    16     
    17     int numDistinct(string S, string T) {
    18         int res = 0;
    19         dfs(S, 0, T, 0, res);
    20         return res;
    21     }
    22 };
  • 相关阅读:
    day08作业
    day07作业
    day06作业
    day05作业
    OOAD与UML
    大数据(3):基于sogou.500w.utf8数据Hbase和Spark实践
    大数据(2):基于sogou.500w.utf8数据hive的实践
    大数据(1):基于sogou.500w.utf8数据的MapReduce程序设计
    九大排序算法的Java实现
    数字在排序数组中出现的次数
  • 原文地址:https://www.cnblogs.com/easonliu/p/3645801.html
Copyright © 2011-2022 走看看