码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode115 Distinct Subsequences

时间:2016-11-17 23:44:23      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:which   class   动态   pre   bsp   lcs   递推   str   ati   

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

标签:which   class   动态   pre   bsp   lcs   递推   str   ati   

原文地址:http://www.cnblogs.com/wangxiaobao/p/6075830.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!