class Solution {
public int numDistinct(String s, String t) {
int n1 = s.length();
int n2 = t.length();
char[] ch1 = s.toCharArray();
char[] ch2 = t.toCharArray();
// 1.确定dp数组,dp[i][j] 是以是s[i-1]为结尾的字符串s中有dp[i][j]个以t[j-1]为结尾的字符串
int[][] dp = new int[n1+1][n2+1];
// 2.确定递推关系
/**
如果s[i-1]和t[j-1]相等,那么两边就不需要考虑这个相同的字符了;另外
同样需要考虑s中的字符删掉一个之后的情况
if(s[i-1] == t[j-1]){
dp[i][j] = dp[i-1][j-1] + dp[i-1][j];
}else{
dp[i][j] = dp[i-1][j];
}
*/
// 3.初始化
/**
dp[i][0] 以s[i-1]为结尾的字符串s中有多少个以空字符串为结尾的 1个
dp[0][j] 0个
dp[0][0] = 1;
*/
for(int i=0; i<=n1; i++){
dp[i][0] = 1;
}
// 4.遍历顺序 从上到下,从左到右
for(int i=1; i<=n1; i++){
for(int j=1; j<=n2; j++){
if(ch1[i-1] == ch2[j-1]){
dp[i][j] = dp[i-1][j-1] + dp[i-1][j];
}else{
dp[i][j] = dp[i-1][j];
}
}
}
return dp[n1][n2];
}
}
运行结果: