leetcode

    xiaoxiao2026-09-20  12

    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 O(n*m)


    http://www.cnblogs.com/higerzhang/p/4133793.html

    class Solution { public: int numDistinct(string S, string T) { int lenS = S.size(), lenT = T.size(); if (lenS < lenT) return 0; if (lenT == 0) return lenS; int dp[lenS + 1][lenT + 1]; //memset(dp, 0, sizeof(dp)); for (int i = 0; i <= lenS; ++i) dp[i][0] = 1; for (int i = 1; i <= lenS; ++i) for (int j = 1; j <= lenT && j <= i; ++j) { if (i == j) dp[i][j] = S.substr(0, i) == T.substr(0, j); else if (S[i - 1] != T[j - 1]) dp[i][j] = dp[i - 1][j]; else dp[i][j] = dp[i - 1][j -1] + dp[i - 1][j]; } return dp[lenS][lenT]; } };
    转载请注明原文地址: https://ju.6miu.com/read-1312163.html
    最新回复(0)