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, de >"ACE"de> is a subsequence of de >"ABCDE"de> while de >"AEC"de> is not).
Here is an example:
S = de >"rabbbit"de>, T = de >"rabbit"de>
Return de >3de>.
用动态规划思想,从两个字符串的最后往前计算匹配数目,record[i][j]表示T从i到末尾,S从j到末尾的匹配数是多少。我以i为外部循环,则逻辑可以理解为,首先计算长度为1的目标串在源串中的匹配数,然后计算长度为2的目标串在源串中的匹配数,逐渐加长目标串。
如果T的第i个字符与S的第j个字符相同,那么此时的匹配数由两部分构成:
首先是算上S[j]的情况下,S从j到末尾匹配T从i到末尾的数目,即T从i+1到末尾,S从j+1到末尾的匹配数,即record[i+1][j+1]
然后是不算S[j],S从j到末尾匹配T从i到末尾的数目,即record[i][j+1]
因此,主要的递推公式为record[i][j] = record[i + 1][j + 1] + record[i][j + 1];
考虑目标串长度为1的情况,若源串长度也为1,则record[i][j] = 1;
若源串长度不为1,上述两种情况的前者一定为1,因此record[i][j] = 1 + record[i][j + 1];
综上,代码如下:
class Solution {
public int numDistinct(String s, String t) {
int slen = s.length(), tlen = t.length();
if(tlen == 0)
return 1;
if(slen == 0)
return 0;
int[][] record = new int[tlen][slen];
char[] sou = s.toCharArray(), tar = t.toCharArray();
for(int i = tlen - 1; i > -1; i--){
for(int j = slen - 1; j > -1; j--){
if(tar[i] == sou[j]){
if(i < tlen - 1 && j < slen - 1)
record[i][j] = record[i + 1][j + 1] + record[i][j + 1];
if(i == tlen - 1 && j == slen - 1)
record[i][j] = 1;
if(i == tlen - 1 && j < slen - 1)
record[i][j] = 1 + record[i][j + 1];
}
else if(j < slen - 1)
record[i][j] = record[i][j + 1];
}
}
return record[0][0];
}
}