leetcode_491 递增子序列

122 阅读1分钟

要求

给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。

数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。

示例 1:

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

示例 2:

输入:nums = [4,4,3,2,1]
输出:[[4,4]]

提示:

  • 1 <= nums.length <= 15
  • -100 <= nums[i] <= 100

核心代码

class Solution:
    def findSubsequences(self, nums: List[int]) -> List[List[int]]:
        res = []
        self.n = len(nums)
        def dfs(index,path):
            if len(path) >= 2:
                res.append(path)
            if index >= self.n:
                return 
            used = {}
            for i in range(index,self.n):
                if nums[i] in used:
                    continue
                used[nums[i]] = True
                if not path or nums[i] >= path[-1]:
                    dfs(i+1,path + [nums[i]])
        dfs(0,[])
        return res

image.png

重点问题

解题思路:

这个一个深度遍历的问题,对于深度优先遍历的过程,之后会放在手动推导中呈现出来。