#week11
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.
分析
这个和平常的最长子序列的不同的点在于是要求该子序列的个数
因此需要在DP时再加一维用来存放个数
初始化每个状态的每个维都为1
状态变换:
if(dp[i].first == dp[j].first + 1)dp[i].second += dp[j].second;
if(dp[i].first < dp[j].first + 1)dp[i] = {dp[j].first + 1, dp[j].second};
题解
1 class Solution { 2 public: 3 int findNumberOfLIS(vector<int>& nums) { 4 int n = nums.size(), res = 0, max_len = 0; 5 vector<pair<int,int>> dp(n,{1,1}); //dp[i]: {length, number of LIS which ends with nums[i]} 6 for(int i = 0; i<n; i++){ 7 for(int j = 0; j <i ; j++){ 8 if(nums[i] > nums[j]){ 9 if(dp[i].first == dp[j].first + 1)dp[i].second += dp[j].second; 10 if(dp[i].first < dp[j].first + 1)dp[i] = {dp[j].first + 1, dp[j].second}; 11 } 12 } 13 if(max_len == dp[i].first)res += dp[i].second; 14 if(max_len < dp[i].first){ 15 max_len = dp[i].first; 16 res = dp[i].second; 17 } 18 } 19 return res; 20 } 21 };