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
.
关键点是理解DP构造。
在这个DP 二维矩阵中,第一行和第一列分别表示 T为空,和S为空,显然,当T为空时,总是为1。 而S为空时,只有T为空才为1,其他均为0.
解决好第一行和第一列之后,就可以开始build optimum solution了。
拿 DP[3][4]来说吧,我们要求的是T中的rab在S=rabbbit中的最优解。
首先,T的'b' 和 S的'b' 匹配。
然后我们这里有两种选择,一种是选DP[3][4]为匹配,另一种是不选DP[3][4]为匹配而继续。
显然,DP[3][4]的结果应该是选或者不选这两种结果的和。
如果选,那么应该是DP[3-1][4-1] = DP[2][3] 这个最优解,
如果不选,那么应该是DP[3][4-1] = DP[3][3] 这个解,因为即使不匹配,也应该至少有前面已经匹配的解。这里是T中的rab已经和S中的rab匹配了,解是1,那么在DP[3][4]即便不匹配,那么也至少是1
最后把两个解相加,得出2.
如果用递归求解,那么递归式就是:
//recursive DP
public static int numDistinct(String S, String T) {
int[][] dp = new int[S.length()][T.length()];
for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp[0].length; j++) {
dp[i][j] = -1;
}
}
return numDistinctHelper(S, T, 0, 0, dp);
}
private static int numDistinctHelper(String S, String T, int i, int j, int[][] dp) {
if (j == T.length()) return 1;
if (i == S.length()) return 0;
if (dp[i][j] != -1) return dp[i][j];
int count = 0;
if (S.charAt(i) == T.charAt(j))
count = numDistinctHelper(S, T, i + 1, j, dp) + numDistinctHelper(S, T, i + 1, j + 1, dp);
else count = numDistinctHelper(S, T, i + 1, j, dp);
dp[i][j] = count;
return count;
}
// iterator DP solution
public static int numDistinct2(String S, String T){
int[][] memo = new int[T.length()+1][S.length()+1];
for(int i = 0; i < S.length()+1; i++){
memo[0][i] = 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)){
memo[i][j] = memo[i][j-1] + memo[i-1][j-1];
}else{
memo[i][j] = memo[i][j-1];
}
}
}
//System.out.println(Arrays.deepToString(memo));
return memo[T.length()][S.length()];
}