zoukankan      html  css  js  c++  java
  • LeetCode OJ

    题目:

    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[i][j]表示S的前i个字符和T的前j个字符中的解。

     if (S[i - 1] == T[j - 1]) dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];

     else dp[i][j] = dp[i-1][j];

    代码:

    class Solution {
    public:
        int numDistinct(string S, string T) {
            int rows = S.length(), cols = T.length();
            vector<vector<int>> dp(rows + 1, vector<int>(cols + 1, 0));
            for (int i = 0; i < rows; i++) {
                dp[i][0] = 1; // if T is empty, every S has 1 match
            }
    
            for (int i = 1; i <= rows; i++) {
                for (int j = 1; j <= cols; j++) {
                    if (S[i - 1] == T[j - 1]) {
                        // have two situation
                        dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
                    }
                    else {
                        dp[i][j] = dp[i - 1][j];
                    }
                }
            }
            return dp[rows][cols];
        }
    };
  • 相关阅读:
    DS博客作业02—线性表
    DS博客作业01--日期抽象数据类型
    c语言第六次作业---结构体&文件
    c语言博客05--指针
    c语言博客作业04--数组
    DS博客作业08-课程总结
    DS博客作业07--查找
    DS博客作业06--图
    DS博客作业-05--树
    DS-博客作业03--栈和队列
  • 原文地址:https://www.cnblogs.com/dongguangqing/p/3727975.html
Copyright © 2011-2022 走看看