题目原型:
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
.
基本思路:
根据递推式 t[i][j] = t[i][j-1] + (S[i]==T[j])?t[i-1][j-1]:0(i字符串T的下标,j是字符串S的下标)得出。
public int numDistinct(String S, String T) { int[][] num = new int[T.length()+1][S.length()+1]; //初始化边缘条件 for(int i = 0;i<S.length();i++) num[0][i] = 0; for(int i = 0;i<T.length();i++) num[i][0] = 0; for(int indexS = 1;indexS<=S.length();indexS++) { for(int indexT = 1;indexT<=indexS&&indexT<=T.length();indexT++) { if(S.charAt(indexS-1)==T.charAt(indexT-1)) { //当T的长度为1时 if(indexT==1) num[indexT][indexS] = num[indexT][indexS-1]+1; else num[indexT][indexS] = num[indexT][indexS-1]+num[indexT-1][indexS-1]; } else num[indexT][indexS] = num[indexT][indexS-1]; } } return num[T.length()][S.length()]; }
Distinct Subsequences,布布扣,bubuko.com
原文:http://blog.csdn.net/cow__sky/article/details/21879905