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;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/196056.html
標籤:其他
上一篇:【翻譯】威脅捕捉成熟度模型
