https://leetcode.com/problems/distinct-subsequences/#/description
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).
Here is an example:
S = "rabbbit"
, T = "rabbit"
Return 3
.
package go.jacob.day713;
/**
* 115. Distinct Subsequences
* @author Jacob
*
*/
public class Demo2 {
/*
* 行列交换结果是一样的
*/
public int numDistinct(String s, String t) {
if(s==null||t==null)
return 0;
int[][] res=new int[s.length()+1][t.length()+1];
for(int i=0;i<=s.length();i++){
res[i][0]=1;
}
for(int i=0;i<s.length();i++){
for(int j=0;j<t.length();j++){
if(s.charAt(i)==t.charAt(j))
res[i+1][j+1]=res[i][j]+res[i][j+1];
else
res[i+1][j+1]=res[i][j+1];
}
}
return res[s.length()][t.length()];
}
public int numDistinct_1(String s, String t) {
if(s==null||t==null)
return 0;
int[][] res=new int[t.length()+1][s.length()+1];
for(int i=0;i<=s.length();i++){
res[0][i]=1;
}
for(int i=0;i<t.length();i++){
for(int j=0;j<s.length();j++){
if(t.charAt(i)==s.charAt(j))
res[i+1][j+1]=res[i][j]+res[i+1][j];
else
res[i+1][j+1]=res[i+1][j];
}
}
return res[t.length()][s.length()];
}
}