【动态规划】子序列问题 最长递增子序列的个数

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


一.关于求最大值个数的小demo

        接下来我用一段代码来解释如何求一串数字中的最大值

#include<iostream>
#include<vector>
using namespace std;

int main()
{
    vector<int> nums = {2, 2, 1, 3, 2, 3, 3};
    int count = 1, max_num = nums[0];
    for(int i = 1; i < nums.size(); i++)
    {
        if(max_num == nums[i])
            count++;
        if(max_num < nums[i])
            count = 1, max_num = nums[i];
    }
    cout << count << endl;

}

         所以我们利用这个算法思想来统计最长递增子序列出现的次数。


二.题目介绍  


三.状态分析  

         这里更新len[i] 最长长度同样重要,长度的更新是辅助个数更新的,一旦长度更新有误最后的返回结果一定是错误的。


四.完整代码     

int findNumberOfLIS(vector<int>& nums) 
    {
        int n = nums.size(), res_len = 1, res_count = 1;
        vector<int> len(n, 1), count(n, 1);
        for(int i = 1; i < n; i++)
        {
            for(int j = i-1; j >= 0; j--)
            {
                if(nums[i] > nums[j]) //此条件成立才进行len和count的更新
                {
                    if(len[j] + 1 == len[i])
                        count[i] += count[j];
                    if(len[j] + 1 > len[i])
                        len[i] = len[j] + 1, count[i] = count[j];
                }
            }
            // 每一个位置遍历完开始统计结果
            if(res_len == len[i])
                res_count += count[i];
            if(res_len < len[i])
                res_len = len[i], res_count = count[i];
        }

        return res_count;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值