Number of Longest Increasing Subsequence (M)
题目
Given an integer array nums
, return the number of longest increasing subsequences.
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:
0 <= nums.length <= 2000
-10^6 <= nums[i] <= 10^6
题意
统计给定数组中最长递增子序列的个数。
思路
动态规划。建两个数组len和cnt:len[i]表示以第i个整数为结尾的递增子序列的长度,cnt[i]表示以第i个整数为结尾的递增子序列的个数。目标就是求len[i]最大时的cnt[i]的值。
代码实现
Java
class Solution {
public int findNumberOfLIS(int[] nums) {
if (nums.length == 0) {
return 0;
}
int[] len = new int[nums.length];
int[] cnt = new int[nums.length];
len[0] = 1;
cnt[0] = 1;
for (int i = 1; i < nums.length; i++) {
int maxLen = 0, maxCnt = 1;
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
if (len[j] > maxLen) {
maxLen = len[j];
maxCnt = cnt[j];
} else if (len[j] == maxLen) {
maxCnt += cnt[j];
}
}
}
len[i] = maxLen + 1;
cnt[i] = maxCnt;
}
int maxLen = 0, maxCnt = 0;
for (int i = 0; i < nums.length; i++) {
if (len[i] > maxLen) {
maxLen = len[i];
maxCnt = cnt[i];
} else if (len[i] == maxLen) {
maxCnt += cnt[i];
}
}
return maxCnt;
}
}