673. Number of Longest Increasing Subsequence

本文介绍了一种使用动态规划算法寻找数组中最长递增子序列数量的方法,并提供了具体的实现示例。对于长度不超过2000的整数数组,通过两层循环实现了O(n^2)的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Hint:
要找一个序列的最长递增子序列的数目,可以使用动态规划算法。

len[i]:前i项的最长子序列长度。
count[i]:记录前i项的最长子序列数目。
nums[i]:原输入串第i项

当i > j, nums[i] > nums[j]时, 意味着第i项可以与以第j项结尾的递增子序列结合成更长的递增子序列。
因此对每个i遍历它的前面所有项,找出所有满足nums[i] > nums[j]的j,计算出最长的一个递增子序列max{1+len[j]},即为len[i]的值。

len[i] = 1 + max{len[i], 1+len[j]} i > j, nums[i] > nums[j]

对count[i],当我们每次发现一个1+len[j]与当前len[i] (即当前所知最长子序列长度) 相等时,我们需要在count[i]基础上加上可以达到len[j]的所有可能count[j],即count[i] += count[j]。而当我们发现1+len[j]>len[i],意味着最长递增子序列的长度更新了,因此以前的count[i]不再是最长子序列的个数,要把count[i]重置。

最后找出max{len[i]},统计对应count,即为答案

时间复杂度O(n^2)

class Solution {
public:
    int findNumberOfLIS(vector<int>& nums) {
        int size = nums.size();
        vector<int> len(size,1);
        vector<int> count(size,1);
        int maxlen = 1;
        for (int i = 0; i < size; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i]) {
                    if (len[i] < 1+len[j]) {
                        len[i] = 1+len[j];
                        count[i] = count[j];
                    } else if (len[i] == 1+len[j]) {
                        count[i] += count[j];
                    }
                }
            }
            maxlen = max(maxlen,len[i]);
        }
        int result = 0;
        for (int i = 0; i < size; i++) {
            if (len[i] == maxlen) {
                result += count[i];
            }
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值