[LeetCode] 115. Distinct Subsequences_ Hard tag: Dynamic Programming
2024-08-26 19:30:57
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"
Explanation: As shown below, there are 3 ways you can generate "rabbit" from S.
Output: 3
(The caret symbol ^ means the chosen letters)rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^
Example 2:
Input: S ="babgbag"
, T ="bag"
Explanation: As shown below, there are 5 ways you can generate "bag" from S.
Output: 5
(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]
最新文章
- Linux学习日记(二)
- MongoDB基础入门001--安装
- EF的性能改善和思考
- Python 监控nginx服务是否正常
- 常用的JAVA集合讲解
- linux设备驱动归纳总结(三):3.设备驱动面向对象思想和lseek的实现【转】
- Redis 内存使用优化与存储
- F. Igor and Interesting Numbers
- utmp, wtmp, and lastlog 日志清除工具
- bzoj2561: 最小生成树
- T-SQL备忘(1):表联接
- DbProviderFactories.GetFactory Oracle.ManagedDataAccess.Client
- php 实现购物车
- HibernateTemplate实现查询distinct构造对象
- 游戏服务器设计之NPC系统
- 论文翻译:Neural Networks With Few Multiplications
- java 得到目录路径的方法
- linux命令重定向>;、>;>;、 1>;、 2>;、 1>;>;、 2>;>;、 <;
- Atom编辑器中安装Emmet插件失败的问题
- WebLogic: 内存溢出