13.11—动态规划—Distinct Subsequences

来源:互联网 发布:tplink访客网络是什么 编辑:程序博客网 时间:2024/06/06 18:12
描述
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.

#include<iostream>#include<string>using namespace std;int DistinctSubsequences(string S, string T)//二维DP{int len1 = S.size();int len2 = T.size();if (len2 > len1)return 0;int **p = new int*[len1 + 1];for (int i = 0; i <= len1; i++)p[i] = new int[len2 + 1];for (int i = 0; i <= len1; i++)//初始化二维数组{for (int j = 0; j <= len2; j++){if (j == 0)p[i][j] = 1;elsep[i][j] = 0;}}for (int i = 1; i <= len1; i++){for (int j = 1; j <= len2; j++){if (S[i - 1] == T[j - 1])p[i][j] = p[i - 1][j - 1] + p[i - 1][j];elsep[i][j] = p[i - 1][j];}}int res = p[len1][len2];for (int i = 0; i <= len1; i++)delete[]p[i];delete[]p;return res;}int main(){string S = "rabbbit";string T = "rabbit";int res = DistinctSubsequences(S, T);cout << res << endl;}