Leetcode-673. Number of Longest Increasing Subsequence 最长递增子序列的个数 (DP) -python

题目

给定一个未排序的整数数组,找到最长递增子序列的个数。
链接:https://leetcode.com/problems/number-of-longest-increasing-subsequence/

Given an unsorted array of integers, find the number of longest increasing subsequence.

Example:

Input: [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7].

思路及代码

DP
  • dp[i]:包含第i个元素在内的最长子序列的长度
  • count[i]:包含第i个元素在内的最长子序列的个数
  • dp[i] = max(dp[j]) + 1,其中nums[j] < nums[i]
  • count[i] = sum(count[j]),其中j代表了所有max(dp)的index,j<i且nums[j] < nums[i]
  • 返回值sum(count[i]),其中i为max(dp)的所有index
class Solution:
    def findNumberOfLIS(self, nums: List[int]) -> int:
        if not nums:
            return 0
        dp = [1] * len(nums)
        count = [1] * len(nums)
        for i in range(len(nums)):
            prev = 0
            for j in range(i-1, -1, -1):
                if nums[i] > nums[j]:
                    if dp[j] > prev:
                        prev = dp[j]
                        count[i] = count[j]
                    elif dp[j] == prev:
                        count[i] += count[j]
            dp[i] = prev + 1
        lis = max(dp)
        cnt = 0
        for i in range(len(dp)):
            if dp[i] == lis:
                cnt += count[i]
        return cnt

复杂度

T = O ( n 2 ) O(n^2) O(n2)
S = O ( n ) O(n) O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值