【LeetCode】491. 递增子序列

这篇博客介绍了如何解决LeetCode第491题——找到整型数组的所有递增子序列。提供了三种解法:动态规划结合哈希表、深度优先搜索配合哈希表以及广度优先搜索加哈希表。每种方法都详细解释了思路,并给出了代码实现。动态规划法从基础情况开始,逐步扩展递增子序列;深度优先搜索和广度优先搜索则利用哈希表避免重复,确保找到所有递增子序列。
摘要由CSDN通过智能技术生成

题目

给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是2。

示例:

输入: [4, 6, 7, 7]
输出: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]

说明:

  • 给定数组的长度不会超过15。
  • 数组中的整数范围是 [-100,100]。
  • 给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。

解题思路

解法一:动态规划+哈希表

最开始的情况:

{(nums[0], )}

用集合pres来保存,后来扩展,每一步都将当前递增之序列加入pres:

pres.update({j+(i, ) for j in pres if j[-1] <= i})
pres.add((i, ))

返回符合要求的递增子序列。

class Solution:
    def findSubsequences(self, nums: List[int]) -> List[List[int]]:
        if not nums:
            return []
        pres = {(nums[0], )}
        for i in nums[1:]:
            pres.update({j+(i, ) for j in pres if j[-1] <= i})
            pres.add((i, ))
        return list([list(i) for i in pres if len(i) > 1])

解法二:深度优先搜索+哈希表

1、定义返回列表res保存所有递增子序列;

2、深度优先搜索(dfs),参数:nums,tmp保存当前递增子序列;

  • 如果当前递增子序列符合要求:res增加tmp
  • 定义字典保存状态,避免重复!
  • inx, i循环nums的索引值对。
    • 如果当前值在以前已被遍历:跳出当前循环,开始下一次循环。
    • 如果i加入tmp可以形成递增子序列:i为键,1为值加入字典;
      • 递归:
        • nums = nums[inx+1:];
        • tmp = tmp+[i]。

3、调用dfs:

  • nums = nums
  • tmp = []

4、返回res

class Solution:

    def findSubsequences(self, nums: List[int]) -> List[List[int]]:
        res = []

        def dfs(nums: List[int], tmp: List[int]) -> None:
            if len(tmp) > 1:
                res.append(tmp)
            curPres = defaultdict(int)
            for inx, i in enumerate(nums):
                if curPres[i]:
                    continue
                if not tmp or i >= tmp[-1]:
                    curPres[i] = 1
                    dfs(nums[inx+1:], tmp+[i])

        dfs(nums, [])
        return res

解法三:广度优先搜索+哈希表

class Solution:
    def findSubsequences(self, nums: List[int]) -> List[List[int]]:
        res = []
        d = deque([(nums, [])])
        while d:
            cur, new = d.popleft()
            if len(new) > 1:
                res.append(new)
            curPres = defaultdict(int)
            for inx, i in enumerate(cur):
                if curPres[i]:
                    continue
                if not new or i >= new[-1]:
                    curPres[i] = 1
                    d.append((cur[inx+1:], new+[i]))
        return res

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值