zoukankan      html  css  js  c++  java
  • LeetCode115 Distinct Subsequences

    Given a string S and a string T, count the number of distinct subsequences of T in S. (Hard)

    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.

    分析:

    看题目感觉就跟LCS很像,考虑用双序列动态规划解决。

    1. 状态:

    dp[i][j]表示从第一个字符串前i个组成的子串转换为第二个字符串前j个组成的子串共有多少种方案。

    2. 递推:

    s[i - 1] == t[j - 1], 则dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];

    s[i - 1] != t[j - 1],则dp[i][j] = dp[i - 1][j];

    3. 初始化:

    dp[i][0] = 1(删除到没有字符只有一种方案)

    4. 返回值:

    dp[sz1 - 1][sz2 - 1]

    代码:

     1 class Solution {
     2 public:
     3     int numDistinct(string s, string t) {
     4         int sz1 = s.size(), sz2 = t.size();
     5         int dp[sz1 + 1][sz2 + 1];
     6         memset(dp, 0 , sizeof(dp));
     7         for (int i = 0; i < sz1; ++i) {
     8             dp[i][0] = 1;
     9         }
    10         for (int i = 1; i <= sz1; ++i) {
    11             for (int j = 1; j <= sz2; ++j) {
    12                 if (s[i - 1] == t[j - 1]) {
    13                     dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
    14                 }
    15                 else {
    16                     dp[i][j] = dp[i - 1][j];
    17                 }
    18             }
    19         }
    20         return dp[sz1][sz2];
    21     }
    22 };
  • 相关阅读:
    计算机术语
    【转】 物理内存和线性空间
    windows Visual Studio 上安装 CUDA【转载】
    windows Notepad++ 上配置 vs 编译器 , 编译并运行
    单列模式 [转载]
    Java Swing布局管理器GridBagLayout的使用示例 [转]
    五年java工作应具备的技能
    三年java软件工程师应有的技技能
    京东面试题 Java相关
    京东笔试题总结
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/6075830.html
Copyright © 2011-2022 走看看