dp!感觉地推公式好难想 用了一个m*n矩阵 下面是讲解 递推看了讲解感觉能看懂 但是在0位置多出一行一列 并且初始化的数并不能很直观的想出来
/**
* Solution (DP):
* We keep a m*n matrix and scanning through string S, while
* m = T.length() + 1 and n = S.length() + 1
* and each cell in matrix Path[i][j] means the number of distinct subsequences of
* T.substr(1...i) in S(1...j)
*
* Path[i][j] = Path[i][j-1] (discard S[j])
* + Path[i-1][j-1] (S[j] == T[i] and we are going to use S[j])
* or 0 (S[j] != T[i] so we could not use S[j])
* while Path[0][j] = 1 and Path[i][0] = 0.
*/
public class Solution {
public int numDistinct(String s, String t) {
if ( s == null || t == null )
return 0;
int m = s.length();
int n = t.length();
if ( m < n )
return 0;
int [][] res = new int [ n + 1 ][ m + 1 ];
for ( int i = 0; i <= m; i ++ )
res [ 0 ][ i ] = 1;
for ( int i = 1; i <= n; i ++ ){
for ( int j = 1; j <= m; j ++ ){
if ( s.charAt( j - 1 ) == t.charAt( i - 1 ) )
res [ i ][ j ] = res [ i ][ j - 1 ] + res [ i - 1 ][ j - 1 ];
else
res [ i ][ j ] = res [ i ][ j - 1 ];
}
}
return res [ n ][ m ];
}
}