题目描述
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.
思路
动态规划问题,设dp[i][j]表示S.subsequence(0, i)中不重复的T.subsequence(0, j)的个数,对于T来说,如果T[i] != S[i],则dp[i][j] = dp[i-1][j],加入第i个字符没有增益,如果T[i] == S[i],则dp[i][j]的来源有两个,j字符加入或者j字符不加入,这两种情况的个数都能原封不动的继承,所以dp[i][j] = dp[i-1][j-1] + dp[i-1][j]
代码
public class Solution {
public int numDistinct(String S, String T) {
int sLen = S.length();
int tLen = T.length();
int dp[] = new int[tLen+1];
dp[0] = 1;
for (int i=0; i<sLen; i++){
for (int j=tLen; j>0; j--){
if (S.charAt(i) == T.charAt(j-1)){
dp[j] = dp[j] + dp[j-1];
}
}
}
return dp[tLen];
}
}
网友评论