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.
这道题意思是说,给定两个字符串,S和T,寻找T在S的子序列中出现的次数。
这道题和Eidt Distance类似,都是动态规划的题。
起初想用一个一维数组来做标记数组,但是写起来有一定难度,于是,借鉴了一下别人的思路,然后,在讨论区发现一个理解起来特别简单的方法(https://leetcode.com/discuss/26680/easy-to-understand-dp-in-java)。整理如下
使用一个二维数组dp[T.length+1][S.length+1]做标记。
比如给定两个字符串S:dabdsdsadfsfdes
T:ad
定义一个标记数组:dp[T.length+1][S.length+1];
S:dabdsdsadfsfdes
首先,我们寻找a:dp[1]=[ 0111112222222]
然后,寻找ad: dp[2]=[ 0001122244466]
程序如下:
public int numDistinct(String S, String T) {
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=0; i<T.length(); i++) {
for(int j=0; j<S.length(); j++) {
if(T.charAt(i) == S.charAt(j)) {
mem[i+1][j+1] = mem[i][j] + mem[i+1][j];
} else {
mem[i+1][j+1] = mem[i+1][j];
}
}
}
return mem[T.length()][S.length()];
}