LeetCode 673.最长递增子序列的个数

LeetCode 673.最长递增子序列的个数

给定一个未排序的整数数组,找到最长递增子序列的个数。

示例 1:

输入: [1,3,5,4,7]
输出: 2
解释: 有两个最长递增子序列,分别是 [1, 3, 4, 7] 和[1, 3, 5, 7]。
示例 2:

输入: [2,2,2,2,2]
输出: 5
解释: 最长递增子序列的长度是1,并且存在5个子序列的长度为1,因此输出5。

dp[i]:i前最长递增子序列的长度

新增一个计数数组count,如果dp[j]+1==dp[i]就说明有两组最长递增子序列

nums: 1 3 5 4 7
count:1 2 3 3 4
1 3 5
1 3 4
class Solution {
public:
    int findNumberOfLIS(vector<int>& nums) {
        int n=nums.size();
        if(n==0)
            return 0;
        vector<int> dp(n,1),count(n,1);
        int ans=0,maxn=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];
                    maxn=max(maxn,dp[i]);
                }
            }
        for(int i=0;i<n;++i)
            if(dp[i]==maxn)
                ans+=count[i];
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/PegasiTIO/article/details/89047930