• 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.

    思路:

    DP。

    用r[i][j]表示S的前i的子串包含多少T的前j的子串。

    如果S[i] == T[j], r[i][j] = r[i-1][j] + r[i-1][j-1]

    如果S[i] !=  T[j], r[i][j] = r[i-1][j]。

    代码:

     1 int numDistinct(string S, string T) {
     2         // Start typing your C/C++ solution below
     3         // DO NOT write int main() function
     4         int col = S.length() + 1;
     5         int row = T.length() + 1;
     6         int** dp = new int*[row];
     7         for(int i = 0; i < row; ++i)
     8             dp[i] = new int[col];
     9         
    10         for(int i = 0; i < row; ++i)
    11             dp[i][0] = 0;
    12         for(int j = 0; j < col; ++j)
    13             dp[0][j] = 1;
    14         
    15         for(int i = 1; i < row; ++i)
    16             for(int j = 1; j < col; ++j)
    17                 if(T[i-1] == S[j-1]) dp[i][j] = dp[i-1][j-1] + dp[i][j-1];
    18                 else dp[i][j] = dp[i][j-1];
    19                 
    20         int tmp = dp[row-1][col-1];
    21         
    22         for(int i = 0; i < row; ++i)
    23             delete[] dp[i];
    24         delete[] dp;
    25         return tmp;
    26     }

     第二次

     1 int numDistinct(string S, string T) {
     2         // Start typing your C/C++ solution below
     3         // DO NOT write int main() function
     4         int ls = S.length(), lt = T.length();
     5         int res[ls+1][lt+1];
     6         int i,j;
     7         for(i = 0; i <= lt; i++)
     8             res[0][i] = 0;
     9         for(i = 0; i <= ls; i++)
    10             res[i][0] = 1;
    11         for(i = 1; i <= ls; i++){
    12             for(j = 1; j <= lt; j++){
    13                 if(S[i-1] == T[j-1])
    14                     res[i][j] = res[i-1][j-1]+res[i-1][j];
    15                 else
    16                     res[i][j] = res[i-1][j];
    17             }
    18         }
    19         return res[ls][lt];
    20     }
  • 相关阅读:
    static 静态
    纽扣电池带负载能力差
    JAVA--异常(1)
    【DP专题】——洛谷P1273有线电视网
    我到现在都没有搞明白git233333
    git常见问题之git pull origin master时fatal: refusing to merge unrelated histories
    矩阵内积转化为求矩阵乘积的迹
    矩阵分解系列三:非负矩阵分解及Python实现
    矩阵分解系列三:可对角化矩阵的谱分解
    矩阵分解系列二:正交三角分解(UQ、QR分解)
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3417639.html
Copyright © 2020-2023  润新知