[LeetCode] 673. Number of Longest Increasing Subsequence

本文介绍了一种使用动态规划求解LeetCode上一道关于寻找最长递增子序列数量的问题的方法。通过两个数组len和cnt分别记录最长子序列的长度及对应数量,逐步更新并找出所有可能的最长递增子序列及其数量。

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

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

Description

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.

解题思路

动态规划求解,建立两个数组 lencnt
* len[k]: 表示以 nums[k] 为末尾的最长子序列长度。
* cnt[k]: 表示以 nums[k] 为末尾的最长子序列个数。

对于每一个 nums[i],只需要遍历其前面的所有数字 nums[j] (0 <= j < i) ,找到比它小且长度最长的 nums[k],就可得出以 nums[i] 为末尾的子序列的最大长度 len[i] = len[k] + 1 。同时,以 nums[i] 为末尾的最长子序列个数应该等于 nums[j] (0 <= j < i) 中,比它小且长度最长的所有 nums[k] 的最长子序列个数之和。

用两条公式来阐述上面一段难以理解的话
* len[k] = max(len[k], len[i] + 1), for all 0 <= i < k and nums[i] < nums[k]
* cnt[k] = sum(cnt[i]), for all 0 <= i < k and len[k] = len[i] + 1

举个例子

nums = {1, 3, 5, 4, 7}

初始状态,len = {1, 1, 1, 1, 1}cnt = {1, 1, 1, 1, 1}

开始遍历,
* 数字 3,比它小的只有 1 => len[1] = len[0] + 1 = 2cnt[1] = cnt[0] = 1
* 数字 5,比它小且长度最长的为 3 => len[2] = len[1] + 1 = 3cnt[2] = cnt[1] = 1
* 数字 4, 比它小且长度最长的为 3 => len[3] = len[1] + 1 = 3cnt[3] = cnt[1] = 1
* 数字 7,比它小且长度最长的为 5 和 4 => len[4] = len[2] + 1 = 4cnt[4] = cnt[2] + cnt[3] = 2

最终状态,len = {1, 2, 3, 3, 4}cnt = {1, 1, 1, 1, 2}

Code

class Solution {
public:
    int findNumberOfLIS(vector<int>& nums) {
        int maxLen = 1;
        int res = 0;
        vector<int> len(nums.size(), 1);
        vector<int> cnt(nums.size(), 1);

        for (int i = 1; i < nums.size(); ++i) {
            for (int j = 0; j < i; ++j) {
                if (nums[j] < nums[i]) {
                    if (len[j] + 1 > len[i]) {
                        len[i] = len[j] + 1;
                        cnt[i] = cnt[j];
                    } else if (len[j] + 1 == len[i]) {
                        cnt[i] += cnt[j];
                    }
                }
            }
            maxLen = max(maxLen, len[i]);
        }


        for (int i = 0; i < nums.size(); ++i) {
            if (maxLen == len[i]) res += cnt[i];
        }

        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值