博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Lintcode]118. Distinct Subsequences/[Leetcode]115. Distinct Subsequences
阅读量:5094 次
发布时间:2019-06-13

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

/

  • 本题难度: Medium/Hard
  • Topic: Dynamic Programming

Description

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

Given S = "rabbbit", T = "rabbit", return 3.

Challenge

Do it in O(n^2) time and O(n) memory.

O(n^2) memory is also acceptable if you do not know how to optimize memory.

我的代码

class Solution:    """    @param S: A string    @param T: A string    @return: Count the number of distinct subsequences    """    def numDistinct(self, S, T):        # write your code here        ls = len(S)        lt = len(T)        if lt == 0:            return 1        res = [0 for _ in range(ls)]        for i in range(ls):            if S[i] == T[0]:                res[i] = 1        for i in range(1,lt):            pre_sum = 0            for j in range(ls):                now = res[j]                if S[j] == T[i]:                    res[j] = pre_sum                else:                    res[j] = 0 #忘记更新了                pre_sum += now        return sum(res)

思路

一开始想模仿的思路,初始设定空间复杂度为O(n^2)
“dp[i][j] 对S中S[:i+1]和T[:j+1]有多少种情况,当S[i]==T[j]时,如“rabb”和“rab”等于“r”和“ra”的情况+1”
但是突然发现新增加的元素可能在前面就会有重复,所以应该分成两部分来看,即“ra”在S各个位置的情况+各个位置之后“b”的情况。
然后我模拟了一下res的变化,发现res的变化很有规律,可以in-place更新。所以空间复杂度变成了O(n)

S = "rabbbit", T = "rabbit",           r a b b b i tr          1 0 0 0 0 0 0   1ra         0 1 0 0 0 0 0   1rab        0 0 1 1 1 0 0   3rabb       0 0 0 1 2 0 0   3rabbi      0 0 0 0 0 3 0   3rabbit     0 0 0 0 0 0 3   3
  • 时间复杂度: O(mn)
  • 空间复杂度: O(n)
  • 出错
    忘记更新在S[j] != T[i]时的res[i][j]=0

转载于:https://www.cnblogs.com/siriusli/p/10390036.html

你可能感兴趣的文章
Python列表
查看>>
Node.js & Unix/Linux & NVM
查看>>
UVA11752 The Super Powers —— 数论、枚举技巧
查看>>
P进制转Q进制
查看>>
D3之svg transform 与 css3 transform 区别与联系
查看>>
.NET Oject And Json
查看>>
python学习笔记__Python的安装
查看>>
iOS设置拍照retake和use按钮为中文简体
查看>>
以下内容为Stackoverflow上整理以作纪录
查看>>
工业机器人常用语言---val语言介绍
查看>>
python3的包(package)在centos中的安装地址
查看>>
(3)Deep Learning之神经网络和反向传播算法
查看>>
Java Spring boot 企业微信点餐系统
查看>>
保持长宽比 对背景图像进行修改android:scaleType="fitXY"
查看>>
python-上传下载文件
查看>>
【转】如何解决:Android中 Error generating final archive: Debug Certificate expired on 10/09/18 16:30 的错误...
查看>>
HttpClient短信接口
查看>>
echo print printf() sprintf()区别
查看>>
https阿里云证书购买与apache环境配置
查看>>
21个js 技巧收藏
查看>>