LeetCode.491 递增子序列 Python3

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Victordas/article/details/82559094

给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是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]。
给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况

自己搞了半天写了个很复杂的算法,看了博客https://blog.csdn.net/fuxuemingzhu/article/details/79827505
用深度优先算法解决恍然大悟,不过这个代码有点难懂。。

class Solution:
    def findSubsequences(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        self.dfs(nums, 0, res, [])
        print(res)

    def dfs(self, nums, index, res, path):
        if len(path) >= 2 and path not in res:
            res.append(path.copy())
        for i in range(index, len(nums)):
            if not path or path[-1] <= nums[i]:
                path += [nums[i]]
                self.dfs(nums, i + 1, res, path)
                path.pop()

if __name__ == "__main__":
   Result = Solution()
   Result.findSubsequences(nums=[4, 6, 7, 7])

猜你喜欢

转载自blog.csdn.net/Victordas/article/details/82559094