leetcode算法题-- 最长递增子序列的个数★

原题链接:https://leetcode-cn.com/problems/number-of-longest-increasing-subsequence/

相关题目:最长上升子序列

lengths[j]存储以nums[j]为终点的最长长度
counts[j]存储length[j]的数目

状态转移:

lengths[j]=lengths[i]; counts[j]=counts[i];   if nums[i]>nums[j]&&lengths[i]>=lengths[j]						  
counts[j]+=counts[i];                         if nums[i]>nums[j]&&lengths[i]+1==lengths[j]

代码:

int findNumberOfLIS(vector<int>& nums) {
     
    int size=nums.size();
    vector<int> lengths(size,1);
    vector<int> counts(size,1);
    int max_len=0;
    for(int j=0;j<size;j++){
     
        for(int i=0;i<j;i++){
     
            if(nums[i]<nums[j]){
     
                if(lengths[i]>=lengths[j]){
     
                    lengths[j]=lengths[i]+1;
                    counts[j]=counts[i];
                }else if(lengths[i]+1==lengths[j]){
     
                    counts[j]+=counts[i];//相当于树的分支
                }
            }
        }
        max_len=max(max_len,lengths[j]);
    }
    int ans=0;
    for(int i=0;i<size;i++){
     
        if(max_len==lengths[i]){
     
            ans+=counts[i];
        }
    }
    return ans;
}

你可能感兴趣的:(算法)