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.
这道题目主要要注意的 是 initialize的过程,对于所有的 num[ i ][ 0 ] 都要付值为1
num[ i ][ j ] 表示s 的前i 个数中对于 t 的前j 个数,有多少distinct sequences
public class Solution {
public int numDistinct(String S, String T) {
if (S == null || T == null) {
return 0;
}
int l1 = S.length();
int l2 = T.length();
int[][] num = new int[l1 + 1][l2 + 1];
for (int i = 0; i < l1; i++) {
num[i][0] = 1;
}
for (int i = 0; i < l1; i++) {
for (int j = 0; j < l2; j++) {
if (j > i) {
break;
}
num[i + 1][j + 1] = S.charAt(i) == T.charAt(j) ? (num[i][j] + num[i ][j + 1]) : num[i][j+1];
}
}
return num[l1][l2];
}
}
本文介绍了一种计算一个字符串作为另一个字符串子序列数量的方法。通过动态规划算法,实现了一个解决方案,该方案能够有效地计算出所有不同的子序列数量。
2万+

被折叠的 条评论
为什么被折叠?



