Given a string S and a string T, count the number of distinct subsequences of S which equals T.

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).

Example 1:

Input: S = "rabbbit", T = "rabbit"
Output: 3
Explanation: As shown below, there are 3 ways you can generate "rabbit" from S.
(The caret symbol ^ means the chosen letters) rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^

Example 2:

Input: S = "babgbag", T = "bag"
Output: 5
Explanation: As shown below, there are 5 ways you can generate "bag" from S.
(The caret symbol ^ means the chosen letters) babgbag
^^ ^
babgbag
^^ ^
babgbag
^ ^^
babgbag
^ ^^
babgbag
^^^ 这个题目思路是用两个sequence的dynamic programming,mem[l1 + 1][l2 + 1] # mem[i][j]表示number of distinct subsequences of S[: i + 1] which equals T[: j + 1]
mem[i][j] = mem[i - 1][j] + mem[i - 1][j - 1] if s1[i - 1] == s2[j - 1] # 如果相等,可以选择配对或者不配对
       mem[i - 1][j] if s1[i - 1] != s2[j - 1] # 如果不相等,就必须把最后一个舍弃掉 初始化: mem[i][0] = 1, mem[0][j] = 0 (j > 1) code
class Solution:
def disSubsequences(self, s1, s2):
l1, l2 = len(s1), len(s2)
mem = [[0] * (l2 + 1) for _ in range(l1 + 1)]
for i in range(l1 + 1):
mem[i][0] = 1
for i in range(1, l1 + 1):
for j in range(1, l2 + 1):
mem[i][j] = mem[i - 1][j] if s1[i - 1] != s2[j - 1] else mem[i - 1][j] + mem[i - 1][j - 1]
return mem[l1][l2]

最新文章

  1. Linux学习日记(二)
  2. MongoDB基础入门001--安装
  3. EF的性能改善和思考
  4. Python 监控nginx服务是否正常
  5. 常用的JAVA集合讲解
  6. linux设备驱动归纳总结(三):3.设备驱动面向对象思想和lseek的实现【转】
  7. Redis 内存使用优化与存储
  8. F. Igor and Interesting Numbers
  9. utmp, wtmp, and lastlog 日志清除工具
  10. bzoj2561: 最小生成树
  11. T-SQL备忘(1):表联接
  12. DbProviderFactories.GetFactory Oracle.ManagedDataAccess.Client
  13. php 实现购物车
  14. HibernateTemplate实现查询distinct构造对象
  15. 游戏服务器设计之NPC系统
  16. 论文翻译:Neural Networks With Few Multiplications
  17. java 得到目录路径的方法
  18. linux命令重定向>、>>、 1>、 2>、 1>>、 2>>、 <
  19. Atom编辑器中安装Emmet插件失败的问题
  20. WebLogic: 内存溢出

热门文章

  1. [原创]Xilinx工具关联UEStudio
  2. python---单向循环链表实现
  3. Crypto支付宝模块的安装
  4. java 安装以及配置
  5. Linux基础系统优化
  6. angular中service封装$http做权限时拦截403等状态及获取验证码倒计时、跨域问题解决
  7. [BZOJ1045][HAOI2008]糖果传递 (环形均分纸牌)
  8. silverlight 调试问题
  9. node环境配置
  10. ECMA Script 6_函数的扩展