115. Distinct Subsequences (String; DP)

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]表示 # of T[0...j-1] in S[0...i-1] (dp[0][0]表示s=NULL,t=NULL的情况)

如果S[i]!=T[j],那么dp[i][j]=dp[i-1][j]

如果S[i]=T[j],dp[i][j]=dp[i-1][j]+j抽出的情况=dp[i-1][j]+dp[i-1][j-1] (注意:这里并不是简单的dp[i-1][j]+1, j抽出后,dp[i-1][j-1]是要大于dp[i-1][j]的)

class Solution {
public:
int numDistinct(string s, string t) {
int sLen = s.length();
int tLen = t.length();
vector<vector<int>> dp(sLen+, vector<int>(tLen+,));
for(int i = ; i <= sLen; i++){ //if t==NULL, 1 method to match
dp[i][]=;
} for(int i = ; i <=sLen; i++){
for(int j = ; j <= tLen; j++){
if(s[i-]==t[j-]){
dp[i][j]=dp[i-][j]+dp[i-][j-];
}
else{
dp[i][j]=dp[i-][j];
}
}
}
return dp[sLen][tLen];
}
};
上一篇:OC 继承子类对象调用方法机制 子类对象访问父类中的实例变量


下一篇:(笔记)Mysql命令mysql:连接Mysql数据库