题目
给定一个未排序的整数数组,找到最长递增子序列的个数。
链接: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)