今天遇到LEETCODE的第115题: Distinct Subsequences

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
^^^

解法1:动态规划
假设已经得到了s[:i]中所有的t串f(i,t),考虑s[i]和t[-1]这2个字符,if不等:f(i+1,t)=f(i,t);else:f(i+1,t)=f(i,t)+f(i+1,t[:-1])。于是解法如下:
def dp(s,t):
  if len(s)<len(t):return 0
  if len(t)==1:return s.count(t)
  ans=dp(s[:-1],t)
  if s[-1]==t[-1]:ans+=dp(s[:-1],t[:-1])
return ans
测试中发现对比较长的S,出现了超时错误,说明时间复杂度高(O(len(s)*len(t)))。 解法2:二分法
对S进行等长分割成left,right,则结果应该=left中的数量 + right中的数量 + 跨界的数量
其中,跨界的数量 = left中的t[:1]数量*right中的t[1:]数量 + left中的t[:2]数量*right中的t[2:]数量 +...+ left中的t[:-1]数量*right中的t[-1]数量
于是解法如下:
def dp(s,t):
            print(s,t)
            if len(s)<len(t):return 0
            if len(t)==1:return s.count(t)
            n=len(s)//2
            left,right=s[:n],s[n+1:]
            ans=dp(left,t)+dp(right,t)
            for i in range(1,len(t)):
                ans+=dp(left,t[:i])*dp(right,t[i:])
            return ans
测试中发现对比较长的S,出现了超时错误,说明时间复杂度高(O(len(s)*len(t)))。同时也说明跨界的数量不能直接算出的话,最好不要用二分法。 解法3:动态规划
再回到解法1,这次用二维转移矩阵,令f(i,j)=s[:i]中t[:j]的数量,考虑s[i]和t[j]这2个字符,if不等:f(i+1,j+1)=f(i,j);else:f(i+1,j+1)=f(i,j)+f(i+1,j)。于是解法如下:
def dp(s,t): res = [[0] * (len(s) + 1) for _ in range(len(t) + 1)]
res[0] = [1] * (len(s) + 1) for i, cht in enumerate(t):
for j, chs in enumerate(s):
if cht == chs:
res[i + 1][j + 1] = res[i][j] + res[i + 1][j]
else:
res[i + 1][j + 1] = res[i + 1][j] return res[-1][-1]
进一步优化为:

def dp(s,t):
   li=[0]*len(t)
   d={}
   for i in range(len(t)):
      d[t[i]]=d.get(t[i],[])+[i]
   for i in range(len(s)):
      print(i,li,end=' ')
      if s[i] in t:
         for j in reversed(d[s[i]]):
            if j == 0:
               li[0] += 1
            else:
               li[j] += li[j - 1]
      print(li)
   return li[-1]

所有不同的序列串-----LCS算法的变种的更多相关文章

  1. 对LCS算法及其变种的初步研究

    LCS的全称为Longest Common Subsequence,用于查找两个字符串中的最大公共子序列,这里需要注意区分子序列与子串,所谓子序列,指的是从前到后,可以跳跃元素筛选,而字串则必须连续筛 ...

  2. LCS算法

    转自:http://hzzy-010.blog.163.com/blog/static/79692381200872024242126/  好详细~~~也十分好理解~~~ 最长公共子序列问题(非连续的 ...

  3. 最大公共字串LCS问题(阿里巴巴)

    给定两个串,均由最小字母组成.求这两个串的最大公共字串LCS(Longest Common Substring). 使用动态规划解决. #include <iostream> #inclu ...

  4. 序列最小最优化算法(SMO)-SVM的求解(续)

    在前一篇文章中,我们给出了感知器和逻辑回归的求解,还将SVM算法的求解推导到了最后一步,在这篇文章里面,我们将给出最后一步的求解.也就是我们接下来要介绍的序列最小最优化算法. 序列最小最优化算法(SM ...

  5. 【机器学习】支持向量机(SVM)的优化算法——序列最小优化算法(SMO)概述

    SMO算法是一一种启发式算法,它的基本思路是如果所有变量的解的条件都满足最优化问题的KKT条件,那么这个最优化问题的解就得到了.因为KKT条件是该优化问题的充分必要条件. 整个SMO算法包括两个部分: ...

  6. 笔试算法题(30):从已排序数组中确定数字出现的次数 & 最大公共子串和最大公共序列(LCS)

    出题:在已经排序的数组中,找出给定数字出现的次数: 分析: 解法1:由于数组已经排序,所以可以考虑使用二分查找确定给定数字A的第一个出现的位置m和最后一个出现的位置n,最后m-n+1就是A出现的次数: ...

  7. O(nlogn)LIS及LCS算法

    morestep学长出题,考验我们,第二题裸题但是数据范围令人无奈,考试失利之后,刻意去学习了下优化的算法 一.O(nlogn)的LIS(最长上升子序列) 设当前已经求出的最长上升子序列长度为len. ...

  8. LCS 算法实现

    动态规划算法 #include <iostream> #include <string.h> #include <algorithm> #include <m ...

  9. Levenshtein Distance + LCS 算法计算两个字符串的相似度

    //LD最短编辑路径算法 public static int LevenshteinDistance(string source, string target) { int cell = source ...

随机推荐

  1. 用Xshell在centos7下安装lnmp服务

    虚拟机已创建好,本机已安装Xshell 一.准备工作:安装常用工具 1.1  yum install -y vim 备注:-y是同意安装过程中的询问,不被询问打断安装 vim:vim是一个类似于Vi的 ...

  2. windows 10, v1903 正式版下载

    一.简体中文版 cn_windows_10_business_editions_version_1903_x64_dvd_e001dd2c.iso         sha1:bc6176bee6130 ...

  3. call 和 apply方法解析

    ECAMScript 3给Function的原型定义了两个方法,它们是 `Function.prototype.call` 和 `Function. prototype.apply`.在实际开发中,特 ...

  4. iOS has conflicting provisioning settings 解法

    *:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } ...

  5. Python单元测试框架unittest

    学习接口自动化测试时接触了unittest单元测试框架,学习时参照了虫师编写的<selenium2自动化测试实战>,个人觉得里面讲的例子还比较容易理解的. 一.基础 1.main()和框架 ...

  6. Yum安装时出现 The program yum-complete-transaction is found in the yum-utils package

    yum安装时出现 The program yum-complete-transaction is found in the yum-utils package yum之后,会显示上信息,并且最终执行结 ...

  7. leetcode算法题01

    最近求职需要重新刷算法题,从今天开始每天至少做一个leatcode的题 如果有更好的算法或者换了语言也会更新 题目: 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只 ...

  8. 也谈开源GIS架构实现思想

    针对业务发展需要,需要开发设计一套具备自己独立GIS平台.然而以ArcGIS为主的GIS软件价格昂贵,在经过仔细技术与市场动向调研后,确立一套以Java语言的开源GIS软件平台.桌面CS端Udig+G ...

  9. 第 9 章 数据管理 - 075 - 配置 VirtualBox backend

    配置 VirtualBox backend 在 VirtualBox 宿主机上启动 vboxwebsrv 服务: C:\Program Files\Oracle\VirtualBox > VBo ...

  10. 详解MySQL中concat函数的用法(连接字符串)

    MySQL中concat函数 使用方法: CONCAT(str1,str2,…) 返回结果为连接参数产生的字符串.如有任何一个参数为NULL ,则返回值为 NULL. 注意: 如果所有参数均为非二进制 ...