673. Number of Longest Increasing Subsequence

Given an unsorted array of integers, find the number of longest increasing subsequence.

Example 1:

Input: [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7].

Example 2:

Input: [2,2,2,2,2]
Output: 5
Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5.

Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int.


分析

设lengths[i]为以nums[i]结尾的最长子序列的长度,counts[i]为以nums[i]为以nums[i]结尾的最长子序列的数量。

对于某个j,对于每个i,i满足i<j且nums[i]<nums[j]:

如果lengths[i] >= length[j],说明我们发现了更长的子序列,以nums[j]结尾,将length[j]更新为length[i]+1,count[j]=count[i];

如果lengths[i]+1=length[j],说明还有counts[i]个以nums[j]结尾的子序列,所以counts[j]+=counts[i];

如果lengths[i]+1<length[j],则无需更新,什么也不做。

找出最大的lengths[i]为longest;

计数longest的数目。


class Solution {
public:
    int findNumberOfLIS(vector<int>& nums) {
		int N = nums.size();
        if (N <= 1) return N;
        int lengths[N]; //lengths[i] = length of longest ending in nums[i]
        int counts[N]; //count[i] = number of longest ending in nums[i]
        for (int i = 0; i < N; ++i) {
        	counts[i]=1;
        	lengths[i]=1;
        } 

        for (int j = 0; j < N; ++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];
                }
            }
        }

        int longest = 0, ans = 0;
        for (int i = 0; i < N; ++i) {
            longest = max(longest, lengths[i]);
        }
        for (int i = 0; i < N; ++i) {
            if (lengths[i] == longest) {
                ans += counts[i];
            }
        }
        return ans;      
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值