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.

动态规划

思路

  0 r a b b b i t
0 1 1 1 1 1 1 1 1
r 0 1 1 1 1 1 1 1
a 0 0 1 1 1 1 1 1
b 0 0 0 1 2 3 3 3
b 0 0 0 0 1 3 3 3
i 0 0 0 0 0 0 3 3
t 0 0 0 0 0 0 0 3  

state: dp[i][j] 表示S串中从开始位置到第i位置与T串从开始位置到底j位置匹配的子序列的个数
function: dp[i][j] = dp[i][j-1] 就是说假设S已经匹配了j-1个字符,无论S[j]和T[i]是否匹配, 至少是dp[i][j-1]
如果匹配(S[j]和T[i]匹配)让S[j - 1]和T[i - 1]去匹配 (由图得关系)
dp[i][j] += dp[i-1][j-1]
initial: f[i][0] = 0 f[0][j] = 1 空集也是subsequences
return dp[m][n]

复杂度

时间O(mn) 空间O(mn)

代码

public int numDistinct(String s, String t) {
    int[][] dp = new int[t.length() + 1][s.length() + 1];
    dp[0][0] = 1;
    
    for (int j = 0; j <= t.length(); j++) {
        dp[j][0] = 0;
    }
    for (int i = 0; i <= s.length(); i++) {
        dp[0][i] = 1;
    }
    for (int i = 1; i <= t.length(); i++) {
        for (int j = 1; j<= s.length(); j++) {
            dp[i][j] = dp[i][j - 1];
            if (s.charAt(j - 1) == t.charAt(i - 1)) {
                dp[i][j] += dp[i - 1][j - 1];
            }
        }
    }
    return dp[t.length()][s.length()];
}

lpy1990
26 声望10 粉丝