Given an integer array nums, return the number of longest increasing subsequences.
Notice that the sequence has to be strictly increasing.
Example 1:
Input: nums = [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input: nums = [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.
Constraints:
1 <= nums.length <= 2000
-106 <= nums[i] <= 106
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-longest-increasing-subsequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
用两个dp数组,一个len[i]表示,到第i个数字,最长的子序列的长度。count[i]表示,第i个数字,最长的子序列的个数。
class Solution {
public int findNumberOfLIS(int[] nums) {
if (nums.length <= 1) {
return nums.length;
}
int []len = new int[nums.length];
Arrays.fill(len, 1);
int []count = new int[nums.length];
Arrays.fill(count, 1);
int max = 0;
int maxCount = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
if (len[i] == len[j] + 1) {
// 说明 nums[i] 这个数字可以加在以 nums[j] 结尾的递增序列后面
// 则以 nums[j] 结尾的递增序列个数可以直接加到以 nums[i] 结尾的递增序列个数上
count[i] += count[j];
} else if (len[i] < len[j] + 1) {
// 说明找到了一条长度更长的递增序列,直接更新len[i]和count[i],与j保持一致
len[i] = len[j] + 1;
count[i] = count[j];
}
}
}
// 更新最终长度与最终答案
if (len[i] == max) {
maxCount += count[i];
} else if (len[i] > max) {
max = len[i];
maxCount = count[i];
}
}
return maxCount;
}
}