题目描述
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"
Return3.
题目意思:只能通过删除字符的形式将S变为T,求有多少种方法?
典型动态规划题目。
递推关系是:dp[i][j]表示0~i的String变化为0~j的String的方法数。
dp[x][0]表示S变为空串就只有一种方法。
如果S的第i个位置和T的第j个位置不同,那么该位置元素必然要删除,那么dp[i][j] = dp[i-1][j]
扫描二维码关注公众号,回复:
11117894 查看本文章
如果S的第i个位置和T的第j个位置相同,可以删,也可不删,那么dp[i][j] = dp[i-1][j-1] + dp[i-1][j]
最终dp[S.length()][T.length()]就是最终的答案。
public class Solution {
public int numDistinct(String S, String T) {
if(S == null || S.length() == 0)
return 0;
int[][] dp = new int[S.length()+1][T.length()+1];
dp[0][0] = 1;
for(int i=1; i<S.length()+1; i++) {
dp[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)){
dp[i][j] = dp[i-1][j]+dp[i-1][j-1];;
}else{
dp[i][j] = dp[i-1][j];
}
}
}
return dp[S.length()][T.length()];
}
}