-
Notifications
You must be signed in to change notification settings - Fork 523
/
Copy path30. Number of Longest Increasing Subsequence.cpp
61 lines (52 loc) · 1.31 KB
/
30. Number of Longest Increasing Subsequence.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
Number of Longest Increasing Subsequence
========================================
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
-106 <= nums[i] <= 106
*/
class Solution
{
public:
int findNumberOfLIS(vector<int> &nums)
{
int n = nums.size();
if (n < 2)
return n;
vector<pair<int, int>> dp(n, {1, 1});
int maxlen = 1;
int ans = 1;
for (int i = 1; i < n; i++)
{
for (int j = i - 1; j >= 0; j--)
{
if (nums[j] >= nums[i])
continue;
if (dp[j].first + 1 > dp[i].first)
{
dp[i].first = dp[j].first + 1;
dp[i].second = dp[j].second;
}
else if (dp[j].first + 1 == dp[i].first)
dp[i].second += dp[j].second;
}
if (dp[i].first > maxlen)
{
maxlen = dp[i].first;
ans = dp[i].second;
}
else if (dp[i].first == maxlen)
ans += dp[i].second;
}
return ans;
}
};