LeetCode354. Russian Doll Envelopes——动态规划

文章目录

一、题目

You are given a 2D array of integers envelopes where envelopesi = wi, hi represents the width and the height of an envelope.

One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.

Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).

Note: You cannot rotate an envelope.

Example 1:

Input: envelopes = \[5,4,6,4,6,7,2,3]

Output: 3

Explanation: The maximum number of envelopes you can Russian doll is 3 (2,3 => 5,4 => 6,7).

Example 2:

Input: envelopes = \[1,1,1,1,1,1]

Output: 1

Constraints:

1 <= envelopes.length <= 105

envelopesi.length == 2

1 <= wi, hi <= 105

二、题解

cpp 复制代码
class Solution {
public:
    static bool cmp(vector<int>& e1,vector<int>& e2){
        return e1[0] < e2[0] || (e1[0] == e2[0] && e1[1] > e2[1]);
    }
    int maxEnvelopes(vector<vector<int>>& envelopes) {
        int n = envelopes.size();
        vector<int> ends(n,0);
        int len = 0;
        sort(envelopes.begin(),envelopes.end(),cmp);
        for(int i = 0;i < n;i++){
            int num = envelopes[i][1];
            int index = binarySearch(ends,len,num);
            if(index == -1) ends[len++] = num;
            else ends[index] = num;
        }
        return len;
    }
    int binarySearch(vector<int>& ends,int len,int num){
        int l = 0, r = len - 1,res = -1;
        while(l <= r){
            int mid = (l + r) / 2;
            if(ends[mid] >= num){
                res = mid;
                r = mid - 1;
            }
            else l = mid + 1;
        }
        return res;
    }
};
相关推荐
深圳市方中禾科技1 小时前
FZH1625 LCD 驱动芯片深度评测与实战指南
算法·led
我不会起名字3222 小时前
一天一道算法题(34):回溯法的经典例题(子集)
java·数据结构·python·算法·golang·深度优先·力扣
ThornArmor2 小时前
重铸1996|肉体渲染:关节的裂缝:分段模型积木拼装与未成熟的 RSP 矩阵骨骼动画形变
c语言·汇编·c++·python·硬件架构·游戏机
huang5791473 小时前
哈希算法的抗碰撞机制与安全性增强策略4
算法
林浩杨_4 小时前
SIGIR 2026|南京大学:Video-GAR:“通过生成 Query 来验证视频语义理解”的生成增强范式
论文阅读·人工智能·算法
Logic1014 小时前
C语言/数据结构位运算题解:异或XOR找出货船中的“独特载货量“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
Elsa️7464 小时前
算法一周刷题总结
c++·算法
风合星语4 小时前
2026 机器人工程实例(五):让 Allegro Hand 在 MuJoCo 中完成接触抓取——抓取状态机、稳定抬升与受控释放
c++·python·机器人·仿真
小羊没烦恼!4 小时前
Memory 记忆设计讨论:Agent Memory 的数据模型可以怎么设计
java·开发语言·前端·c++·c#
小小程序猴15 小时前
深圳乘路资讯AI培训怎么样?课程靠谱吗?——一套课程可信度评估模型与实证分析
人工智能·算法