首页 > 代码库 > LeetCode115 Distinct Subsequences

LeetCode115 Distinct Subsequences

Given a string S and a string T, count the number of distinct subsequences of T in S. (Hard)

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.

 

分析:

看题目感觉就跟LCS很像,考虑用双序列动态规划解决。

1. 状态:

dp[i][j]表示从第一个字符串前i个组成的子串转换为第二个字符串前j个组成的子串共有多少种方案。

2. 递推:

s[i - 1] == t[j - 1], 则dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];

s[i - 1] != t[j - 1],则dp[i][j] = dp[i - 1][j];

3. 初始化:

dp[i][0] = 1(删除到没有字符只有一种方案)

4. 返回值:

dp[sz1 - 1][sz2 - 1]

 

代码:

 1 class Solution {
 2 public:
 3     int numDistinct(string s, string t) {
 4         int sz1 = s.size(), sz2 = t.size();
 5         int dp[sz1 + 1][sz2 + 1];
 6         memset(dp, 0 , sizeof(dp));
 7         for (int i = 0; i < sz1; ++i) {
 8             dp[i][0] = 1;
 9         }
10         for (int i = 1; i <= sz1; ++i) {
11             for (int j = 1; j <= sz2; ++j) {
12                 if (s[i - 1] == t[j - 1]) {
13                     dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
14                 }
15                 else {
16                     dp[i][j] = dp[i - 1][j];
17                 }
18             }
19         }
20         return dp[sz1][sz2];
21     }
22 };

 

LeetCode115 Distinct Subsequences