题目描述
题目难度:Hard
Given a string S and a string T, count the number of distinct subsequences of S which equals T.
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).
解题思路
原文:https://blog.csdn.net/feliciafay/article/details/42959119
动态规划题目。
以S =“rabbbit”,T = "rabbit"为例:
dp[i][j]表示T的从0开始长度为i的子串和S的从0开始长度为j的子串的匹配的个数。
比如, dp[2][3]表示T中的ra和S中的rab的匹配情况。
(1)显然,至少有dp[i][j] = dp[i][j - 1].
比如, 因为T 中的"ra" 匹配S中的 “ra”, 所以dp[2][2] = 1 。 显然T 中的"ra" 也匹配S中的 “rab”,所以s[2][3] 至少可以等于dp[2][2]。
(2) 如果T[i-1] == S[j-1], 那么dp[i][j] = dp[i][j - 1] + (T[i - 1] == S[j - 1] ? dp[i - 1][j - 1] : 0);
(注意:T[i-1]表示的是T的前i个字符,因为这里的i是从下标0开始的)
比如, T中的"rab"和S中的"rab"显然匹配,
根据(1), T中的"rab"显然匹配S中的“rabb”,所以dp[3][4] = dp[3][3] = 1,
根据(2), T中的"rab"中的b等于S中的"rab1b2"中的b2, 所以要把T中的"rab"和S中的"rab1"的匹配个数累加到当前的dp[3][4]中。 所以dp[3][4] += dp[2][3] = 2;
(3) 初始情况是
dp[0][0] = 1; // T和S都是空串.
dp[0][1 … S.length() ] = 1; // T是空串,S只有一种子序列匹配。
dp[1 … T.length() ][0] = 0; // S是空串,T不是空串,S没有子序列匹配。
AC代码
class Solution {
public int numDistinct(String S, String T) {
// array creation
int[][] mem = new int[T.length()+1][S.length()+1];
// filling the first row: with 1s
for(int j=0; j<=S.length(); j++) {
mem[0][j] = 1;
}
// the first column is 0 by default in every other rows but the first, which we need.
for(int i=1; i<=T.length(); i++) {
for(int j=1; j<=S.length(); j++) {
if(T.charAt(i - 1) == S.charAt(j - 1)) {
mem[i][j] = mem[i - 1][j - 1] + mem[i][j - 1];
} else {
mem[i][j] = mem[i][j - 1];
}
}
}
return mem[T.length()][S.length()];
}
}