LeetCode Distinct Subsequences
2016-03-10 09:19
441 查看
LeetCode解题之Distinct Subsequences
原题
给定两个字符串S和T,求T有多少种从属于S的子序列的情况。或者说S可以删除它自己任意个字符,但是不能改变字符的相对位置,那一共有多少种删法可以使S变为T。注意点:
删除任意个字符包括不删除字符
例子:
输入: s = “rabbbit”, t = “rabbit”
输出: 3
解题思路
典型的动态规划问题,dp[i][j]表示字符串S[:i]和T[:j]的不同子序列数目,如果S[i-1]和T[j-1]不相等,那么只能在S[:i-1]和T[:j]中匹配,即dp[i][j] = dp[i-1][j];而当S[i-1]和T[j-1]相等时,可以是这两个字符正好匹配,也可以忽略S[i-1],使T[j-1]在S[:i-1]中匹配,所以
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]。进一步观察可以将二维数组压缩为一维,只需要从后往前计算即可。
AC源码
[code]class Solution(object): def numDistinct(self, s, t): """ :type s: str :type t: str :rtype: int """ m = len(s) n = len(t) dp = [0 for __ in range(n + 1)] dp[0] = 1 for i in range(m): for j in range(n - 1, -1, -1): if t[j] == s[i]: dp[j + 1] += dp[j] return dp[-1] if __name__ == "__main__": assert Solution().numDistinct("rabbbit", "rabbit") == 3
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
相关文章推荐
- 背水一战 Windows 10 (2) - UI: 概述, 启动屏幕, 屏幕方向
- build st-crowd
- MathType requires a newer version of MT Extra等MathType问题的不兼容性解决方案
- UIWindow 实现遮盖导航条的蒙版
- Mysql 连接数据库超时设置autoReconnect=true
- @RequestParam @RequestBody @PathVariable 等参数绑定注解详解
- jquer “$” 扩展(笔记)
- lintcode-easy-Unique Paths II
- lintcode-easy-Unique Paths
- 非UI线程可不可以更新UI(二)
- 《EasyUI》——给DataGrid动态绑定表头和数据,实现表头与数据的真正解耦
- UITextField - 输入框
- lightOJ 1082 Array Queries
- 关于封装了gevent的request grequest库的使用与讨论
- SPOJ QTREE6 Query on a tree VI 树链剖分
- android 布局xml中 android:fitsSystemWindows="true"的作用
- 自定义easy-ui validatebox 如maxLength()等等校验规则
- 63. Unique Paths II
- RequireJS模块化与GruntJS构建
- easyui-属性汇总