博客
关于我
【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/

你可能感兴趣的文章
Text-to-Image with Diffusion models的巅峰之作:深入解读 DALL·E 2
查看>>
Tensorflow.python.framework.errors_impl.ResourceExhaustedError:无法分配内存[操作:AddV2]
查看>>
TCP基本入门-简单认识一下什么是TCP
查看>>
tableviewcell 中使用autolayout自适应高度
查看>>
Symbolic Aggregate approXimation(SAX,符号聚合近似)介绍-ChatGPT4o作答
查看>>
Orcale表被锁
查看>>
svn访问报错500
查看>>
sum(a.YYSR) over (partition by a.hy_dm) 不需要像group by那样需要分组函数。方便。
查看>>
ORCHARD 是什么?
查看>>
Struts2中使用Session的两种方法
查看>>
order by rand()
查看>>
Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
查看>>
org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
查看>>
org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
查看>>
org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
查看>>
sqlserver学习笔记(三)—— 为数据库添加新的用户
查看>>
org.apache.ibatis.exceptions.PersistenceException:
查看>>
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
查看>>