Topic links: https://leetcode-cn.com/problems/distinct-subsequences/
Subject description:
Given a string and a string S T, calculate the number of the partial sequences S T appears.
A string is a sequence of sub-means, by eliminating some of (and may not be deleted) does not interfere with the new character string consisting of the relative position of the remaining characters. (E.g., "ACE" is "ABCDE" of a sequence, and "AEC" instead)
Example:
Example 1:
输入: S = "rabbbit", T = "rabbit"
输出: 3
解释:
如下图所示, 有 3 种可以从 S 中得到 "rabbit" 的方案。
(上箭头符号 ^ 表示选取的字母)
rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^
Example 2:
输入: S = "babgbag", T = "bag"
输出: 5
解释:
如下图所示, 有 5 种可以从 S 中得到 "bag" 的方案。
(上箭头符号 ^ 表示选取的字母)
babgbag
^^ ^
babgbag
^^ ^
babgbag
^ ^^
babgbag
^ ^^
babgbag
^^^
Ideas:
Dynamic Programming
dp[i][j]
Representative T
before i
the string may be made S
before the j
strings the maximum number.
So dynamic equation:
When S[j] == T[i]
, dp[i][j] = dp[i-1][j-1] + dp[i][j-1]
;
When S[j] != T[i]
,dp[i][j] = dp[i][j-1]
For example, as in the example of
For the first line, T
it is empty, because empty set is a subset of all the strings, so we are the first line1
For the first column, S
is empty, so that the composition T
number is of course 0
the
As for how to below, we can by dynamic equations, simulate it on their own!
Code:
class Solution:
def numDistinct(self, s: str, t: str) -> int:
n1 = len(s)
n2 = len(t)
dp = [[0] * (n1 + 1) for _ in range(n2 + 1)]
for j in range(n1 + 1):
dp[0][j] = 1
for i in range(1, n2 + 1):
for j in range(1, n1 + 1):
if t[i - 1] == s[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + dp[i][j - 1]
else:
dp[i][j] = dp[i][j - 1]
#print(dp)
return dp[-1][-1]
java
class Solution {
public int numDistinct(String s, String t) {
int[][] dp = new int[t.length() + 1][s.length() + 1];
for (int j = 0; j < s.length() + 1; j++) dp[0][j] = 1;
for (int i = 1; i < t.length() + 1; i++) {
for (int j = 1; j < s.length() + 1; j++) {
if (t.charAt(i - 1) == s.charAt(j - 1)) dp[i][j] = dp[i - 1][j - 1] + dp[i][j - 1];
else dp[i][j] = dp[i][j - 1];
}
}
return dp[t.length()][s.length()];
}
}