Leetcode 673.最长递增子序列的个数

673. 最长递增子序列的个数

题目

给定一个未排序的整数数组,找到最长递增子序列的个数。

1
2
3
4
5
6
7
8
9
10
示例 1:

输入: [1,3,5,4,7]
输出: 2
解释: 有两个最长递增子序列,分别是 [1, 3, 4, 7] 和[1, 3, 5, 7]。
示例 2:

输入: [2,2,2,2,2]
输出: 5
解释: 最长递增子序列的长度是1,并且存在5个子序列的长度为1,因此输出5。

注意: 给定的数组长度不超过 2000 并且结果一定是32位有符号整数。

方法

方法1:动态规划

假设最长递增子序列结束在nums[i],该烈的长度是dp[i],等于该长度dp[i]的递增子序列的个数时count[i]。

对于每一对j<i,且nums[j]<nums[i],可以在以nums[j]为结束点的最长递增子序列A[j]后增加nums[i],获得更长的递增子序列。

count[i]=count[j] if nums[i]>nums[j] and dp[i]<=dp[j]
count[i]+=count[j] if nums[i]>nums[j] and dp[i]==dp[j]+1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution(object):
def findNumberOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0

n=len(nums)
dp=[1]*n # dp[i] = longest ending in nums[i]
count=[1]*n # count[i] = number of longest ending in nums[i]

for i in range(1,n):
for j in range(i):
if nums[i]>nums[j]:
if dp[i]<=dp[j]:
dp[i]=dp[j]+1
count[i]=count[j]
# print('dp[i]<=dp[j]',i,j,dp,count)
elif dp[i]==dp[j]+1:
count[i]+=count[j]
# print('dp[i]==dp[j]+1',i,j,dp,count)
return sum(c for i,c in enumerate(count) if dp[i]==max(dp))