Given a stringSand a stringT, count the number of distinct subsequences ofSwhich equalsT.
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"
Return3
.
Solution: dp[i][j]: S前i个字母和T前j个字母有多少个配对subsequence。看S第i个字母是否与T第j个字母是否配对
dp[i][j] = dp[i - 1][j] + (dp[i - 1][j - 1] if s[i - 1] == t[j - 1])
初始条件:
– 如果B是空串,B在A中出现次数是1
– f[i][0] = 1 (i = 0, 1, 2, …, m)
– 如果A是空串而B不是空串,B在A中出现次数是0
– f[0][j] = 0 (j = 1, 2, …, n)
public int numDistinct(String s, String t) {
if (s == null || s.length() == 0 || t == null || t.length() == 0) {
return 0;
}
int m = s.length(), n = t.length();
int[][] dp = new int[m + 1][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++) {
dp[i][j] = dp[i - 1][j];
if (s.charAt(i - 1) == t.charAt(j - 1)) {
dp[i][j] += dp[i - 1][j - 1];
}
}
}
return dp[m][n];
}