leetcode 673. Number of Longest Increasing Subsequence(最长递增子序列数量DP + BinarySearch)

KLayout教程(二)编辑不同的形状 首先画一个基础的矩形,然后双击他可以定义他的坐标 阅读详情

Given an integer array nums, return the number of longest increasing subsequences.

Notice that the sequence has to be strictly increasing.

Example 1:

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

Input: nums = [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.

给出一个数组,找出其中一共有几个最长子序列

思路:
(1) DP
有两步,一个是找最长递增子序列,一个是最长递增子序列的个数。
那么一个DP数组len保存递增子序列的长度,一个DP数组count保存递增子序列个数。

因为数组不是升序排列的,所以到 i 时,要去和0~i-1所有的元素比较,找到nums[i] > nums[j] ,那么到i 的递增子序列的长度len[ i ]是在len[j] 长度的基础上+1,选择所有len[j]中最大的一个,得到len[i]

同样的,count遍历到i 时,也需要再遍历0~i-1的所有元素, 第一次找到nums[i] > nums[j] 时,可以直接把nums[i]接在nums[ j ]后面,因为它们是同一个子序列,所以count[i] = count[j]。

如果在0~i-1的元素中又发现了新的nums[i] > nums[ j1 ],那么nums[i]也可以接在nums[ j1 ]后面形成新的子序列。这时count[i] = count[j] + count[ j1 ]。
那么如何判断是第一次发现了nums[ j ],还是后面又发现了新的nums[ j1 ]?可以借助长度来判断,如果len[i] == len[j] + 1, 就说明nums[i ] 已经接在在nums[j ]的后面了,如果len[i] < len[j] + 1,,就说明是第一次发现的,还没接成递增子序列。

每次遍历,更新最大子序列的长度。
最后再把数组遍历一次,把序列长度==最大序列长度的count加起来,就是结果。
时间复杂度O(n2)

//33ms
    public int findNumberOfLIS(int[] nums) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        
        int n = nums.length;
        int[] len = new int[n];
        int[] count = new int[n];
        int result = 0;
        int maxLen = 1;
                
        for(int i = 0; i < n; i++) {
            len[i] = 1;
            count[i] = 1;
            for(int j = 0; j < i; j++) {
                if(nums[i] > nums[j]) {
                    if(len[i] == len[j] + 1) {
                        count[i] += count[j];
                    } else if(len[j] + 1 > len[i]) {
                        len[i] = len[j] + 1;
                        count[i] = count[j];
                    }
                    
                    maxLen = Math.max(maxLen, len[i]);
                }
                
            }
        }
        
        for(int i = 0; i < n; i ++) {
            if(len[i] == maxLen) {
                result += count[i];
            }
        }
        
        return result;
    }

(2) BinarySearch
个人认为还是DP思路简单些,虽然说这个方法时间复杂度O(nlogn)
可以想象一下扑克牌游戏的空当接龙,每一竖排的扑克都是从大到小排列的。但是有如下规则:

  1. 当新来一个数字不能再排到第一排的下面时(比最下面的数字大,又不能插到中间),就新开辟一排,把这个新来的数字当首数字。
  2. 当新来一个数字同时满足可以放到第一排和第二排下面时,优先最左边,也就是第一排。

可以参考如下图,参考资料
在这里插入图片描述
所以新来一个数字,首先要在所有竖排中搜索它应该放在第几竖排,这时是和每竖排的最小数字比较(因为规则1,不能在中间插入)。如果最小数字比新来的数字小,就新加一竖排。
如果锁定了某一竖排,就把数字挂在下面,一个竖排的count从上到下累加,这就方便我们可以取任意一段的count和。
如果新开辟一竖排,那么新开辟那个数字的count,就等于它前面一竖排的最小数字到比它大的数字这段的count和(用累加数组相减即可),搜索这个比它大的数字又用到一次Binary search。
举个例子,[1,3,8,5,4,7,6]
1开辟第一竖排, 保存(num, count)

(1, 1)

然后来了3, 比1大,所以又开辟一排,8又开辟一排

(1,1)  (3,1)  (8,1)

然后来了5,比8小,可以挂在8的下面,又来了4,比5小,挂在5的下面,5的累加count=2, 4的累加count是3

(1,1)  (3,1)  (8,1)
              (5,2)
              (4,3)

然后来了7,比所有排的末尾数字都大,不能挂在任何一个下面,所以新开辟一排。那么7的count怎么算呢,算它前面一排,也就是8开头的,这一排最下面的count,减去比7大的数字,也就是8的count,即3-1=2
这个逻辑很简单,可以和7形成递增子序列的,前面应该都是比7小的数,前面的递增子序列一共有3个,其中1,3,8这个序列是不满足后面加上7的,所以找到比7大的第一个数字,它前面的都不满足,就直接减去这个数字的count即可。

(1,1)  (3,1)  (8,1)  (7,2)
              (5,2)
              (4,3)

最后是6,要挂在7下面,同样要搜索它前面一排最后一个数的count,再减去比它大的8的count,同样得到了count=2。因为它挂在7下面,再求这一竖排count的累加和。最终6的count=4.
因为我们计算的时候一竖排的count是累加的,返回的时候只需要返回最后一排的末尾数字的count即可。

(1,1)  (3,1)  (8,1)  (7,2)
              (5,2)  (6,4)
              (4,3)
    public int findNumberOfLIS(int[] nums) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        
        int n = nums.length;
        if(n == 1) {
            return 1;
        }
        List<int[]>[] lists = (List<int[]>[])new ArrayList[n+1]; //List数组
        lists[1] = new ArrayList<int[]>();
        lists[1].add(new int[]{nums[0], 1});
        
        
        int len = 1;  //递增子序列长度,也是竖排的个数
        for(int i = 1; i < n; i++) {
            //搜索竖排
            int L = 1;
            int R = len + 1;
            while(L < R) {
                int M = L + (R-L) / 2;
                List<int[]> cur = lists[M];
                if(cur.get(cur.size()-1)[0] >= nums[i]) {
                    R = M;
                } else {
                    L = M + 1;
                }
            }
            
            if(L - 1 == len) { //要开辟新的一排
                lists[++len] = new ArrayList<int[]>();
            }
            
            int count = 0;
            if(L > 1) { //如果在第一竖排,不需要在前一排搜索了
                List<int[]> pre = lists[L-1];
                //在前一竖排中搜索比新数字大的
                int left = pre.size()-1; //最下面的数字小,上面数字大
                int right = -1;
            
                while(left > right) {
                    int mid = left + (right - left) / 2;
                    if(pre.get(mid)[0] < nums[i]) {
                        left = mid - 1;
                    } else {
                        right = mid;
                    }
                }
                count = pre.get(pre.size()-1)[1] - (left >= 0 ? pre.get(left)[1] : 0);
            } else {
                count = 1;
            }
            
            //当前竖排的count累加
            count += (lists[L].size() == 0) ? 0 : lists[L].get(lists[L].size()-1)[1];
            lists[L].add(new int[]{nums[i], count});
                        
        }
        //最后一排的最后数字的count,注意最后一排不是lists[n]
        return lists[len].get(lists[len].size()-1)[1];
    }
JHU ICBM DTI Atlas纤维束模板介绍 JHU ICBM DTI atlas 纤维束的定位与功能介绍 阅读详情

相关推荐

【无机纳米材料科研制图——OriginLab 0205】Origin对BET吸附/脱附曲线及孔径分布制图...

此篇,我们来分享如何对BET数据进行处理和制图。 一、等温吸脱附曲线绘制 1)找到等温吸脱附文件。 一半来说,对一个样品测一次BET,会产生很多数据,具体因仪器而异。我这里的数据主要有两个文件夹,一个脱附,一个吸附,吸附文件夹中多了一个等温吸脱附的文件夹。而这...

XD_Yangf的博客 808

[leetcode] 673. Number of Longest Increasing Subsequence

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 [...

Learning from the mistakes 233

别再死磕USB HID了!用ESP32的Arduino框架手把手教你实现蓝牙鼠标键盘(附完整代码)

本文详细介绍了如何使用ESP32的Arduino框架实现蓝牙HID设备,包括鼠标和键盘的快速开发。通过现成的库和示例代码,开发者可以轻松打造自定义蓝牙外设,无需复杂的USB HID协议栈,适用于演示控制器、宏键盘等多种场景。

weixin_31309419的博客 270

leetcode【300】【tag DP Binary Search】Longest Increasing Subsequence【c++版本,时间95%,二分查找】

问题描述: Given an unsorted array of integers, find the length of longest increasing subsequence. Example: Input: [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. Note: There may

fanyuwgy的博客 225

考完CAIE认证一年后,谈谈它对我的职业的真实影响(干货)

大门,让面试官愿意给你机会,但进门之后的发展,还得靠持续的学习和项目积累。说实话,当时的心态是“考都考了,总比闲着强”,对这张证书能带来什么实际价值,心里并没有底。这种广泛的生态认可,让这张证书的“流通性”变得很强——无论跳槽还是在原公司发展,它都是一个被市场验证过的能力证明。对我个人而言,虽然没跳槽,但在年度调薪和争取内部项目时,持证经历也成了一个有力的“加分项”。这种巨大的薪资差距,恰恰反映了市场对“能落地、懂技术”的深度人才的渴求。考完证后的这一年,我看到了两条清晰的职业发展路径在自己面前展开。

qq_16014487的博客 825

注册“Oracle Provider for OLE DB”和创建链接服务器

注册“Oracle Provider for OLE DB”和创建链接服务器 在sql server 数据库上创建链接服务器,连接oracle数据库,访问接口需要设置为:“Oracle Provider for OLE DB”。 如果电脑上没有这个驱动,安装一个完整的Oracle11gR2程序是一个有效的方法,但这个64位版本的安装包有2个多G, 相当庞大,如果仅仅...

weixin_30760895的博客 2389

DP O(n)遍历 + Binary Search = O(nlogn)

LeetCode 300. Longest Increasing Subsequence

tree123tree123的博客 386

实测338MB/s!FPGA与CYUSB3014的Slave FIFO模式实战避坑(附完整固件与源码)

本文详细介绍了FPGA与CYUSB3014在Slave FIFO模式下实现338MB/s高速数据传输的实战经验。通过优化硬件设计、固件配置和GPIF II接口设置,解决了USB3.0双向通信中的关键性能瓶颈,并提供了完整的固件与源码参考。

weixin_30570101的博客 459

673. Number of Longest Increasing Subsequence

文章目录1 题目理解2 动态规划 1 题目理解 Given an integer array nums, return the number of longest increasing subsequences. Notice that the sequence has to be strictly increasing. 输入:整数数组int[] nums 输出:最长递增子序列的个数 规则:子序列是指从原数组中找出若干元素组成新的数组。这些元素不一定是下标相邻的,但是元素前后顺序不能变。递增子序列就是新的

约定的博客 282

YOLOv11 损失函数进阶:Varifocal Loss 让正负样本精度双升

创建self.alpha = alpha # 正样本权重系数self.gamma = gamma # 聚焦系数self.lambda_reg = lambda_reg # 回归损失权重# 分类损失:Varifocal Classification Loss# 正样本权重:基于预测置信度# 计算 BCE 损失并加权cls_loss = cls_loss.sum() / (cls_true.sum() + 1e-6) # 按正样本数归一化。

m0_71589036的博客 446

OpenClaw Manager Pro - 可视化管理工具

OpenClaw Manager Pro 是一个现代化的 Web 管理界面,用于管理多个 OpenClaw Gateway 实例。🎨美观的界面:深色主题,渐变设计,现代化 UI📡实时监控:WebSocket 实时推送状态和日志🔧完整管理:创建、编辑、删除、启动、停止 Gateway📊多渠道支持:飞书、Telegram、Discord、Slack、微信、钉钉🧩技能管理:可视化配置 61+ 个技能🌍跨平台:支持 macOS、Linux、Windows使用自定义模型系统会自动在中创建},

Maynor的博客 3092

longest increasing subsequence (最长递增子序列)

转自algorithmist  原文链接 http://www.algorithmist.com/index.php/Longest_Increasing_Subsequence The Longest Increasing Subsequence problem is to find the longest increasing subsequence of a given sequenc

jiaowopan的专栏 1057

手把手教你模拟登录豆瓣并爬取个人书影音数据:从Cookie解析到反爬攻防实战

在开始写代码之前,先明确我们需要的工具。:建议用3.10以上版本,方便使用一些新特性(如match语句)httpx:比requests更现代,支持HTTP/2,异步性能强,连接池复用好:解析HTML,语法简单,容错性强selenium:仅用于处理登录时的滑块验证(模拟真人)pandas:最终数据清洗和导出Excel/CSVretrying:自动重试机制,应对临时封禁:随机UA,降低特征lxml:作为BeautifulSoup的解析器,速度快为什么不只用requests?

2201_76125261的博客 582

LeetCode - 673. Number of Longest Increasing Subsequence(最长递增子序列的个数)

LeetCode - 673. Number of Longest Increasing Subsequence(最长递增子序列的个数) 题目链接 题目 解析 做这题之前先要知道求一个数组的最长递增子序列。 做法: 求出最长递增子序列的长度(max),可以用记忆化也可以递推; 然后遍历数组,看以哪些数结尾的序列是最长序列,然后对每一个这样的序列进行递归处理,从后往前求以这个结尾的最长序列的个数...

zxzxin的博客~ 369

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

[Leetcode] Binary search, DP--300. Longest Increasing Subsequence

Given an unsorted array of integers, find the length of longest increasing subsequence. For example,Given[10, 9, 2, 5, 3, 7, 101, 18],The longest increasing subsequence is[2, 3, 7, 101], there...

weixin_30408309的博客 170

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

【LeetCode】673. Number of Longest Increasing Subsequence 解题报告(Python)

【LeetCode】673. Number of Longest Increasing Subsequence 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/number-of-longest-increasing-subsequence/description/ 题目描述: Given an ...

负雪明烛 2191

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

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]

yanglq的博客 1792

Leetcode题解系列——300. Longest Increasing Subsequence与673. Number of Longest Increasing Subsequenc(c++版)

题目链接:300.Longest Increasing Subsequence 题目大意:最长增长子序列,这是一道经典的动态规划问题。要求输出一串数字的最长增长子序列的长度。 增长子序列,要求nums[i] &amp;lt; nums[j], when i &amp;lt; j. 注意点: 使用动态规划时,序列长度初始的值为1还是0。 注意判断数组长度为0的情况。 一.算法设计 这里有两种时间复杂度的解法。 ...

dick的博客 325

DP Unique Binary Search Trees

思路: DP 关键是要总结出二叉查找树个数的规律。

在路上的学习者 488

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

动态规划基础训练。

raoyx的博客 362

longest continuous subsequence of 0s

How can we find the longest continuous subsequence of 0's in binary representation of an integer in O(log n) time complexity? Michal Forišek, teacher, scientist, c

screaming的博客 397

动态规划-673Number 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,

格物致知 309

leetcode 300: Longest Increasing Subsequence

Longest Increasing Subsequence Total Accepted: 53 Total Submissions: 172 Difficulty: Medium Given an unsorted array of integers, find the length of longest increasing subsequence. For

西施豆腐渣 4457

LintCode 1904: Put small balls (Binary Search + DP)

1904.Put small balls Given the number of balls in n buckets, buckets can be operated k times (one ball can be taken out of the bucket, or one ball can be added), and each bucket has a specified maximum capacity W[i]. Find the minimum square value of the .

roufoo的博客 522

LWC 49:673. Number of Longest Increasing Subsequence

LWC 49:673. Number of Longest Increasing Subsequence传送门:673. Number of Longest Increasing SubsequenceProblem: Given an unsorted array of integers, find the number of longest increasing subsequence. E

Demon-初来驾到 1882

强化学习进阶篇十四 DPO算法

DPO(Direct Preference Optimization,直接偏好优化)由 Rafailov 等人于 2023 年提出。它用「同一个提示词下,回答 A 比回答 B 更合适」这样的成对偏好数据直接微调语言模型。偏好标签可以来自人工标注,也可以像本文的唐诗示例一样按明确规则构造。与采用 PPO 的经典 RLHF 流程相比,DPO 不必单独训练奖励模型,也不必在微调过程中从当前策略在线采样。它从带 KL 正则的奖励最大化目标出发,把奖励改写为当前策略与冻结参考策略的对数概率比,再用 Bradley–T

337
上一篇: leetcode 650. 2 Keys Keyboard(2个键的键盘)
下一篇: leetcode 688. Knight Probability in Chessboard(棋盘中马的概率)
蓝羽飞鸟
博客等级 码龄8年 1万+粉丝 727原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值