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.
截取"bbb" 和 "bb" 出来填表。
0 b b
0 1 0 0
b 1 1 0
b 1 2 1
b 1 3 3
public class Solution {
public int numDistinct(String s, String t) {
int[][] table = new int[s.length() + 1][t.length() + 1];
for(int i=0;i<s.length();i++){
table[i][0] = 1;
}
for(int i=1;i<=s.length();i++){
for(int j=1;j<=t.length();j++){
if(s.charAt(i-1) == t.charAt(j-1)){ // table[i-1][j-1] 且s(i)==t(j) 多了一些路径。
table[i][j] = table[i-1][j] + table[i-1][j-1];
} else { // 这里没有新路径产生,table[i-1][j]就是最大可能的值。
table[i][j] = table[i-1][j];
}
}
}
return table[s.length()][t.length()];
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。