[dp]leetcode673:最长递增子序列的个数(medium)

题目:
在这里插入图片描述
题解:

代码如下:

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;
    }
};
发布了512 篇原创文章 · 获赞 175 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/qq_43152052/article/details/104103165