題目:
題解:
- 動態規劃,在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;
}
};