版权声明:本文为博主原创文章,欢迎转载!转载请保留原博客地址。 https://blog.csdn.net/grllery/article/details/89047128
673. Number of Longest Increasing Subsequence
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.
题目:最长递增子串的个数。
思路:动态规划,参考Simple dp solution with explanation。用length[i]
和count[i]
表示对于子串nums[0...i]
最长的的递增子串,以及对应的个数。
对于任意的i
,(i > j
),如果nums[i] > nums[j]
,有三种情况需要考虑,一种是length[i] < length[j] + 1
那么length[i] = length[j] + 1
,此时count[i] = count[j]
;另一种情况是length[i] == length[j] + 1
,那么length[i]
不改变,count[i] += count[j]
;还有一种情况length[i] > length[j] + 1
,不是最长子串跳过。
最后将length[i] == maxlen
对应的count[i]
求和即可,其中i= 0...n-1
。
class Solution {
public:
int findNumberOfLIS(vector<int>& nums) {
int n = nums.size();
if(n <= 0) return 0;
vector<pair<int, int>> dp(n, {1, 1});
int max_len = 1;
int res = 0;
for(int i = 0; i < n; ++i){
for(int j = 0; j < i; ++j){
if(nums[j] < nums[i]){
if(dp[i].first == dp[j].first + 1)
dp[i].second += dp[j].second;
else if(dp[i].first < dp[j].first + 1)
dp[i] = {dp[j].first + 1, dp[j].second};
}
}
if(dp[i].first == max_len){
res += dp[i].second;
}
else if(dp[i].first > max_len){
max_len = dp[i].first;
res = dp[i].second;
}
}
return res;
}
};