Link: https://oj.leetcode.com/problems/distinct-subsequences/
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.
My thought: I don't understand why output = 3 for the above example. For T, its subsequences = {r, ra, rab, rabb, rabbi, rabbit, a, ab, abb, abbi, ...} are all contained in S.Or does it mean how many complete T are contained in S? Yes.
My first thought: I think this is very similar to Unique Paths, Edit Distance, and Interleaving String
My code:
public class Solution {
public int numDistinct(String S, String T) {
if(S.length() < T.length()) return 0;
int[][] f = new int[S.length()+1][T.length()+1];
for(int j = 0; j < f[0].length; j++){
f[0][j] = 0;
}
for(int i = 0; i < f.length; i++){
f[i][0] = 1;
}
for(int i = 1; i < f.length; i++){
for(int j = 1; j < f[0].length; j++){
if(S.charAt(i-1) == T.charAt(j-1)){
f[i][j] = f[i-1][j-1];
}
else{
f[i][j] = f[i][j-1];
}
}
}
return f[S.length()][T.length()];
}
}
This is wrong. When align S with T, S can have nulls, but T cannot. So f[i][j] can come from f[i-1][j-1], and f[i-1][j] (not f[i][j-1]).
Approach I: 2D-DP
Time: O(mn), Space: O(mn)
public class Solution {
public int numDistinct(String S, String T) {
if(S.length() < T.length()) return 0;
int[][] f = new int[S.length()+1][T.length()+1];
for(int j = 0; j < f[0].length; j++){
f[0][j] = 0;
}
for(int i = 0; i < f.length; i++){
f[i][0] = 1;
}
for(int i = 1; i < f.length; i++){
for(int j = 1; j < f[0].length; j++){
f[i][j] = f[i-1][j];
if(S.charAt(i-1) == T.charAt(j-1)){
f[i][j] += f[i-1][j-1];
}
}
}
return f[S.length()][T.length()];
}
}
Approach II: DP with O(n)
Time: O(mn), Space: O(n)
public class Solution {
public int numDistinct(String S, String T) {
if(S.length() < T.length()) return 0;
int[] f = new int[T.length()+1];
f[0] = 1;
for(int i = 1; i <= S.length(); i++){
for(int j = T.length(); j >= 1; j--){
if(S.charAt(i-1) == T.charAt(j-1)){
f[j] += f[j-1];
}
}
}
return f[T.length()];
}
}
Question: I don't know why we need to loop j decreasingly?
// j应该从尾到头,因为每次要使用上一次loop的值。如果从头往尾扫的话,重复计算了。
Reference: http://fisherlei.blogspot.com/2012/12/leetcode-distinct-subsequences_19.html
But why don't Minimum Path Sum loop j increasingly?