Problem
Given an integer array nums, return the number of longest increasing subsequences.
Notice that the sequence has to be strictly increasing.
Algorithm
Dynamic Programming (DP). Use to lists dp_L[i] and dp_N[i] to save the length and size of longest increasing subsequences of the first i items. Then sum all the items with the longest length.
Code
python3
class Solution:
def findNumberOfLIS(self, nums: List[int]) -> int:
nlen = len(nums)
dp_L = [1] * nlen
dp_N = [1] * nlen
for i in range(1, nlen):
dp_L[i] = 1
dp_N[i] = 1
for j in range(i):
if nums[j] < nums[i]:
if dp_L[i] == dp_L[j] + 1:
dp_N[i] += dp_N[j]
if dp_L[i] <= dp_L[j]:
dp_L[i] = dp_L[j] + 1
dp_N[i] = dp_N[j]
ans = 0
max_l = max(dp_L)
for i in range(nlen):
if max_l == dp_L[i]:
ans += dp_N[i]
return ans