玩命加载中 . . .

115-不同的子序列


LeetCode 115. Distinct Subsequences

LeetCode-115

Given two strings s and t, return the number of distinct subsequences of s which equals t.

A string’s subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters’ relative positions. (i.e., “ACE” is a subsequence of “ABCDE” while “AEC” is not).

The test cases are generated so that the answer fits on a 32-bit signed integer.

Example 1:

Input: s = "rabbbit", t = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from S.

Example 2:
Input: s = "babgbag", t = "bag"
Output: 5
Explanation:
As shown below, there are 5 ways you can generate "bag" from S.

method

dp[i][j]:以i-1结尾的s能能由以j-1结尾的t组成的个数

如果s[i-1]==t[j-1]

  • 可以用s[i-1]来匹配t[j-1],所以dp[i][j]=dp[i-1][j-1],因为可以匹配上,所以个数就不变,相当于加这个字符和没加这个字符结果一样
  • 也可以不用s[i-1],只用s[i-2]来匹配t[j-1],所以dp[i][j]=dp[i-1][j]s没增加,但t增加了一个字符

如果s[i-1]!=t[i-1],就只能删掉s[i-1],用s[0,i-2]来匹配t[0,i-1],所以dp[i][j]=dp[i-1][j]

初始化,如果j=0,则t为空字符串,s只有删除所有字符才会变成空,所以空字符在s中只出现一次,dp[i][0]=1

过程中加法会溢出,所以用uint64_t

int numDistinct(string s, string t) {
    int m = s.size(), n = t.size();
    vector<vector<uint64_t>> dp(m + 1, vector<uint64_t>(n + 1));
    for (int i = 0; i <= m; i++) {
        dp[i][0] = 1;
    }
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; 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];
        }
    }
    return dp[m][n];
}

可以只用一行

int numDistinct(string s, string t) {
    int m = s.size(), n = t.size();
    vector<uint64_t> dp(n + 1);
    dp[0] = 1;
    for (int i = 1; i <= m; i++) {
        for (int j = n; j > 0; j--) {   // 从后往前
            if (s[i - 1] == t[j - 1]) dp[j] += dp[j - 1];
        }
    }
    return dp[n];
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录