博客
关于我
【Leetcode刷题】递增子序列
阅读量:448 次
发布时间:2019-03-06

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

class Solution(object):    def findSubsequences(self, nums):        """nums: List[int]"""        if not nums:            return []                result = []        path = []        n = len(nums)                def trace(start):            if len(path) >= 2:                result.append(path[:])                        memo = set()            for i in range(start, n):                if nums[i] in memo:                    continue                if not path:                    path.append(nums[i])                elif nums[i] >= path[-1]:                    path.append(nums[i])                else:                    continue                memo.add(nums[i])                trace(i + 1)                path.pop()                trace(0)        return result

这个算法通过递归的方式遍历所有可能的子序列,并使用memoization技术来避免重复计算。具体来说,它维护了一个路径记录当前选择的数字序列,以及一个集合来记录已经访问过的数字,以防止重复选择相同的数字。这样可以有效地去重,确保每个子序列都是唯一的。

在时间复杂度方面,尽管看起来是O(n * 2^n),但由于递归函数中有剪枝操作(比如通过memo来跳过已经处理过的数字),实际上的复杂度会有所优化,但仍然保持在O(n * 2^n)的级别。空间复杂度方面,path和memo都只占用O(n)的空间,这使得算法在空间上非常高效。

转载地址:http://tylyz.baihongyu.com/

你可能感兴趣的文章
thinkphp 常用SQL执行语句总结
查看>>
Oracle:ORA-00911: 无效字符
查看>>
Text-to-Image with Diffusion models的巅峰之作:深入解读 DALL·E 2
查看>>
TCP基本入门-简单认识一下什么是TCP
查看>>
tableviewcell 中使用autolayout自适应高度
查看>>
Orcale表被锁
查看>>
svn访问报错500
查看>>
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
查看>>
org.tinygroup.serviceprocessor-服务处理器
查看>>
org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
查看>>
org/hibernate/validator/internal/engine
查看>>