题目:
题解:
- 动态规划,在300. 最长上升子序列的基础上需要记录最长上升子序列的个数。
代码如下:
class Solution {
public:
//题解:动态规划,与300. 最长上升子序列思路一样的,不过要计算最长递增子序列的个数
int findNumberOfLIS(vector<int>& nums) {
if(nums.empty())return 0;
//maxLength记录最长上升子序列长度
int n=nums.size(),maxLength=0;
//dp计算最大递增子序列的长度,count统计最大递增子序列的个数
vector<int> dp(n,1),count(n,1);
for(int i=0;i<n;++i){
for(int j=0;j<i;++j){
if(nums[j]<nums[i]){
if(dp[j]+1>dp[i]){
dp[i]=dp[j]+1;
count[i]=count[j];
}
else if(dp[j]+1==dp[i]){
count[i]+=count[j];
}
}
}
//更新最长子序列长度
maxLength=max(maxLength,dp[i]);
}
//统计最长递增子序列的个数
int res=0;
for(int i=0;i<n;++i){
if(maxLength==dp[i]){
res+=count[i];
}
}
return res;
}
};