博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Distinct Subsequences
阅读量:6231 次
发布时间:2019-06-21

本文共 2280 字,大约阅读时间需要 7 分钟。

Well, a dynamic programming problem. Let's first define its state dp[i][j] to be the number of distinct subsequences of t[0..i - 1] in s[0..j - 1]. Then we have the following state equations:

  1. General case 1: dp[i][j] = dp[i][j - 1] if t[i - 1] != s[j - 1];
  2. General case 2: dp[i][j] = dp[i][j - 1] + dp[i - 1][j - 1] if t[i - 1] == s[j - 1];
  3. Boundary case 1: dp[0][j] = 1 for all j;
  4. Boundary case 2: dp[i][0] = 0 for all positive i.

Now let's give brief explanations to the four equations above.

  1. If t[i - 1] != s[j - 1], the distinct subsequences will not include s[j - 1] and thus all the number of distinct subsequences will simply be those in s[0..j - 2], which corresponds to dp[i][j - 1];
  2. If t[i - 1] == s[j - 1], the number of distinct subsequences include two parts: those withs[j - 1] and those without;
  3. An empty string will have exactly one subsequence in any string :-)
  4. Non-empty string will have no subsequences in an empty string.

Putting these together, we will have the following simple codes (just like translation :-)):

1 class Solution { 2 public: 3     int numDistinct(string s, string t) { 4         int m = t.length(), n = s.length(); 5         vector
> dp(m + 1, vector
(n + 1, 0)); 6 for (int j = 0; j <= n; j++) dp[0][j] = 1; 7 for (int j = 1; j <= n; j++) 8 for (int i = 1; i <= m; i++) 9 dp[i][j] = dp[i][j - 1] + (t[i - 1] == s[j - 1] ? dp[i - 1][j - 1] : 0);10 return dp[m][n];11 }12 };

Notice that we keep the whole m*n matrix simply for dp[i - 1][j - 1]. So we can simply store that value in a single variable and further optimize the space complexity. The final code is as follows.

1 class Solution { 2 public: 3     int numDistinct(string s, string t) { 4         int m = t.length(), n = s.length(); 5         vector
cur(m + 1, 0); 6 cur[0] = 1; 7 for (int j = 1; j <= n; j++) { 8 int pre = 1; 9 for (int i = 1; i <= m; i++) {10 int temp = cur[i];11 cur[i] = cur[i] + (t[i - 1] == s[j - 1] ? pre : 0);12 pre = temp;13 }14 }15 return cur[m];16 }17 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4677471.html

你可能感兴趣的文章
css3 实现逐帧动画
查看>>
zabbix监控交换机、防火墙等网络设备
查看>>
http://www.cnblogs.com/jqyp/archive/2010/08/20/1805041.html
查看>>
WPF样式动画Trigger.EnterActions和Trigger.ExitActions(ExitActions其实可以不做任何事情)
查看>>
Linux IPC System V 消息队列
查看>>
史上最全的 UIWebview 的 JS 与 OC 交互
查看>>
RedHat下安装MySQL
查看>>
SQL Server 2016 需要单独安装 SSMS
查看>>
[译]AngularJS $apply, $digest, 和$evalAsync的比较
查看>>
小尝试一下 cocos2d
查看>>
Android 基于Android的手机邮件收发(JavaMail)之四(邮件的发送)
查看>>
BUPT2017 wintertraining(15) #3 题解
查看>>
js-ES6学习笔记-Set和Map数据结构
查看>>
Xamarin.Forms的滚动视图ScrollView
查看>>
【面试题整理】数据库的优化方案有哪些
查看>>
hdu-5015-233 Matrix-矩阵
查看>>
Android中asset文件夹和raw文件夹区别与用法
查看>>
poj3264
查看>>
Eclipse中git插件导入远程库和上传项目源代码到远程库
查看>>
linux内核剖析-IBM
查看>>