LeetCode Number of Longest Increasing Subsequence

时间:2021-06-02 06:49:31

原题链接在这里:https://leetcode.com/problems/number-of-longest-increasing-subsequence/description/

题目:

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

Example 1:

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

Example 2:

Input: [2,2,2,2,2]
Output: 5
Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5.

Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int.

题解:

len[i] reqpresents到i的LIS长度. count[i] represents 到i的LIS个数.

Base Case 都是1.

For all j from 0 to i, if nums[j] < nums[i], there is a chance to update longest length ending at i.

If there is an update, then update len[i] with len[j]+1 and frequency = count[j].

If there is no update, but len[j]+1 == len[i] means there is other paths to construct LIS ending at i, thus accumlate frequency.

After iterating all j, if longest LIS got update, then update max length, and its frequency.

If max length stays the same, that means globally there is other LIS with the same length, accumate frequency.

Time Complexity: O(n^2), n = nums.length.

Space: O(n).

AC Java:

 class Solution {
public int findNumberOfLIS(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
} int n = nums.length;
// Longest length ending at i
int [] len = new int[n]; // Frequency of longest length ending at i
int [] count = new int[n];
int max = 1;
int res = 0; for(int i = 0; i<n; i++){
len[i] = 1;
count[i] = 1;
for(int j = 0; j<i; j++){
if(nums[j] < nums[i]){
if(len[j]+1 == len[i]){
// Same longest length ending at i, accumlate frequency
count[i] += count[j];
}else if(len[j]+1 > len[i]){
// There is longer subsequence ending at i, update its longest length and frequency
len[i] = len[j]+1;
count[i] = count[j];
}
}
} if(len[i] > max){
// Globally, this one is longer, update global maximum length and its requency
max = len[i];
res = count[i];
}else if(len[i] == max){
// Globally, this one has the same maximum length, accumlate its frequency to res
res += count[i];
}
} return res;
}
}

Longest Increasing SubsequenceLongest Continuous Increasing Subsequence 的进阶题.

跟上Minimum Window Subsequence.