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.
我的思路:是不对的。
class Solution {
public:
struct comp{
bool operator()(const pair<int,int>& a,const pair<int,int>& b){
return a.first<b.first;
}
};
//这种代码是错误的,因为重复
int findNumberOfLIS(vector<int>& nums) {
//这道题不能使用最长递增子序列长度的二分方法,因为那种方法只保存了每个长度结尾的最小值,不含有相同长度的子序列统计值
//但是我们可以尝试把那个存储结尾最小值的数组改成一个pair,first保存当前的最小值,如果出现了替换,就增大second值。
//时间复杂度应该是nlog(n)的,使用lower_bound的自定义比较函数
vector<pair<int,int>> res;
for(int i=0;i<nums.size();i++)
{
pair<int,int> temp=make_pair(nums[i],0);
auto it=lower_bound(res.begin(),res.end(),temp,comp());
if(it==res.end())
res.push_back(make_pair(nums[i],1));
else
{
(*it).first=nums[i];
(*it).second++;
}
}
return res.size()?res[res.size()-1].second:0;
}
};
第二种错误解法:res存储的是当前长度的字串的数量。这个统计是不完整的
class Solution {
public:
int findNumberOfLIS(vector<int>& nums) {
vector<int> dp(nums.size(),1);//以当前字符结尾的长度
vector<int> res(nums.size()+1,0);
res[1]=nums.size();//长度为1的字串有n个
for(int i=1;i<nums.size();i++)
{
for(int j=i-1;j>=0;j--)
if(nums[i]>nums[j])
{
int temp=dp[j]+1;
res[temp]++;
dp[i]=max(dp[i],temp);
}
}
int r=0;
for(int i=nums.size();i>=0;i--)
if(res[i]>0)
{
r=res[i];
break;
}
return r;
}
};
正确答案:
class Solution {
public:
int findNumberOfLIS(vector<int>& nums) {
vector<int> dp(nums.size(),1);//以当前字符结尾的最大长度
vector<int> res(nums.size(),1);//以当前字符结尾的最大长度的个数
int maxLen=1;
for(int i=1;i<nums.size();i++)
{
for(int j=0;j<i;j++)
{
if(nums[i]>nums[j]&&dp[j]+1>dp[i])
{
dp[i]=dp[j]+1;
res[i]=res[j];
}
else if(nums[i]>nums[j]&&dp[j]+1==dp[i])
res[i]+=res[j];
}
maxLen=max(maxLen,dp[i]);
}
int n=0;
for(int i=0;i<nums.size();i++)
if(dp[i]==maxLen)
n+=res[i];
return n;
}
};