【算法分析与设计】【第十一周】673. Number of Longest Increasing Subsequence

本文介绍LeetCode 673题“最长递增子序列数量”的解题思路与实现方法,通过动态规划求解最长递增子序列的长度及数量。

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

题目来源:673:https://leetcode.com/problems/number-of-longest-increasing-subsequence/description/

动态规划基础训练。

673. Number of Longest Increasing Subsequence

题目大意

求出一个无序整数数组的最长递增子序列的数量。

题目有点绕,其实分解一下就是:
(1)求出最长递增子序列的长度len
(2)求长度为len的递增子序列有几条
题目就是求这个条数。


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

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.

思路

其实本质是最长递增子序列问题(LIS)。
只要在求最长递增子序列长度的同时计数就可以了。

  1. 求LIS的长度
    (1)维护数组length,length[i]用于记录以第i个元素为最后一个元素的递增子序列的长度;
    (2)考虑第j个元素:
    将第0~j-1个元素中有小于第j个元素的元素放入集合S,在集合S中找出length最大的si,将第j个元素放到si后面。

  2. 求最长递增子序列长度的同时计数


LIS简单回顾

关于LIS可参考《算法概论》P157

算法

for j = 1, 2, ..., n
  L(j) = 1 + max{L(i):(i, j)∈E}
return maxjL(j)

解题代码

class Solution {
public:
  int findNumberOfLIS(vector<int>& nums) {
    int n = nums.size();

    // handle special case
    if (n <= 1) return n;

    int length[n] = {1};  // length[i] : the length of the seq ends with the ith element
    int count[n] = {1};  // count[i] : the number of seqs of length i
    for (int i = 0; i < n; i++) length[i] = count[i] = 1;

    for (int j = 0; j < n; j++) {
      for (int i = 0; i < j; i++) {
        if (nums[j] > nums[i]) {
          if (length[i] >= length[j]) {
            // add nums[j] into the seq which ends with the ith element, and the length becomes length[i]+1
            length[j] = length[i] + 1;
            count[j] = count[i];
          } else if (length[i] + 1 == length[j]) {
            // merge two seqs
            count[j] += count[i];
          }
        }
      }
    }

    int maxLen = 0;
    for (int i = 0; i < n; i++) {
      if (length[i] > maxLen) maxLen = length[i];
    }
    int re = 0;
    for (int i = 0; i < n; i++) {
      if (length[i] == maxLen) {
        re += count[i];
      }
    }
    return re;
  }
};

时间复杂度

O(n^2)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值