Distinct Subsequences

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,T中對應字符串的變換方法!
s[i] == t[j] 則 dp[i][j] = dp[i-1][j] + dp[i-1][j-1] ;//要麼保留要麼拋棄

dp[i][j] = dp[i-1][j];//不等只能丟掉.

初始化時,注意會出現dp[0][0] ,dp[0][j],dp[i][0]的情況!

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int numDistinct(string S, string T) ;

int main()
{
	string S,T;
	cin>>S>>T;
	cout<<numDistinct(S,T)<<endl;
	return 0;
}

//dp[i][j] S,T中對應字符串的變換方法!
//s[i] == t[j] 則 dp[i][j] = dp[i-1][j] + dp[i-1][j-1] ;//要麼保留要麼拋棄
int numDistinct(string S, string T) 
{
	
	if (T.size() == 0)
	{
		return S.size()==0?0:1;
	}
	if(S.size() < T.size() )
		return 0;

	vector<vector<int>>  dp(S.size()+1, vector<int>(T.size()+1,0));
 

	  dp[0][0] = 1;
	  
	 for (int i = 1; i <= S.size();i++)//針對s存在,t爲空串!
	  dp[i][0] = 1;
	 
	 for (int i = 1; i <= S.size();i++)
	 {
		  for (int j = 1; j <= i&&j <= T.size();j++)
		  {

				if (S[i-1] == T[j-1])
				{
					dp[i][j] = dp[i-1][j] + dp[i-1][j-1];//相等的情況
				}
				else
				{
					dp[i][j] = dp[i-1][j];//不等只能丟掉
					cout<<dp[i-1][j]<<endl;
				}
				 
		  }
	 }

	return dp[S.size()][T.size()];
	 
} 
 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章