• [LeetCode] Distinct Subsequences


    Well, a dynamic programming problem. Let's first define its state dp[i][j] to be the number of distinct subsequences of t[0..i - 1] in s[0..j - 1]. Then we have the following state equations:

    1. General case 1: dp[i][j] = dp[i][j - 1] if t[i - 1] != s[j - 1];
    2. General case 2: dp[i][j] = dp[i][j - 1] + dp[i - 1][j - 1] if t[i - 1] == s[j - 1];
    3. Boundary case 1: dp[0][j] = 1 for all j;
    4. Boundary case 2: dp[i][0] = 0 for all positive i.

    Now let's give brief explanations to the four equations above.

    1. If t[i - 1] != s[j - 1], the distinct subsequences will not include s[j - 1] and thus all the number of distinct subsequences will simply be those in s[0..j - 2], which corresponds to dp[i][j - 1];
    2. If t[i - 1] == s[j - 1], the number of distinct subsequences include two parts: those withs[j - 1] and those without;
    3. An empty string will have exactly one subsequence in any string :-)
    4. Non-empty string will have no subsequences in an empty string.

    Putting these together, we will have the following simple codes (just like translation :-)):

     1 class Solution {
     2 public:
     3     int numDistinct(string s, string t) {
     4         int m = t.length(), n = s.length();
     5         vector<vector<int>> dp(m + 1, vector<int> (n + 1, 0));
     6         for (int j = 0; j <= n; j++) dp[0][j] = 1;
     7         for (int j = 1; j <= n; j++)
     8             for (int i = 1; i <= m; i++)
     9                 dp[i][j] = dp[i][j - 1] + (t[i - 1] == s[j - 1] ? dp[i - 1][j - 1] : 0);
    10         return dp[m][n];
    11     }
    12 };

    Notice that we keep the whole m*n matrix simply for dp[i - 1][j - 1]. So we can simply store that value in a single variable and further optimize the space complexity. The final code is as follows.

     1 class Solution {
     2 public:
     3     int numDistinct(string s, string t) {
     4         int m = t.length(), n = s.length();
     5         vector<int> cur(m + 1, 0);
     6         cur[0] = 1;
     7         for (int j = 1; j <= n; j++) { 
     8             int pre = 1;
     9             for (int i = 1; i <= m; i++) {
    10                 int temp = cur[i];
    11                 cur[i] = cur[i] + (t[i - 1] == s[j - 1] ? pre : 0);
    12                 pre = temp;
    13             }
    14         }
    15         return cur[m];
    16     }
    17 };
  • 相关阅读:
    爬取校园新闻首页的新闻
    网络爬虫基础练习
    综合练习:词频统计
    Hadoop综合大作业
    理解MapReduce
    熟悉常用的HBase操作
    熟悉常用的HDFS操作
    爬虫大作业
    数据结构化与保存
    使用正则表达式,取得点击次数,函数抽离
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4677471.html
Copyright © 2020-2023  润新知