题目
给定一个未排序的整数数组,找到最长递增子序列的个数。
示例
示例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。
关键思路
使用动态规划思想解决,本题为原题的升级版,可以一边求解dp,一边计算当前最长递增子序列的个数。
由于爷在算法课上学过,这边不多做赘述。
代码实现
class Solution(object):
def findNumberOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.insert(0, -float("inf"))
dp = [ 0 for i in range(len(nums)) ]
c = [ 1 for i in range(len(nums))]
length,result = 0,0
for i in range(1, len(nums)):
for j in range(i):
if nums[j]<nums[i]:
if dp[i]<dp[j]+1:
dp[i] = dp[j]+1
c[i] = c[j] # inherit
elif dp[i]==dp[j]+1:
c[i] = c[i] + c[j] # add
if dp[i]>length: # update
length = dp[i]
result = c[i]
elif dp[i]==length: # the same max number
result = result + c[i]
return result
运行结果
2
5
总结反思
算法课,yyds!
链接
https://leetcode-cn.com/problems/number-of-longest-increasing-subsequence