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;
    }
};
相关推荐
yangdaxiageo1 分钟前
算法时代的“心智置顶“:《功夫女足》如何构建GEO正向飞轮
人工智能·科技·算法·aigc
坚定学代码2 分钟前
C++ SOLID 原则(上):单一职责、开闭原则与里氏替换
c++
ysa05103017 分钟前
【板子】欧拉序
c++·笔记·算法·深度优先·图论
不负岁月无痕20 分钟前
STL -- C++ 红黑树封装 Map 和 Set
java·c语言·开发语言·c++·面试
大耳朵糊涂21 分钟前
链表的基础操作(二)
算法
拂拉氏26 分钟前
【知识讲解】 红黑树的删除讲解
数据结构·算法·红黑树
初学者,亦行者27 分钟前
算法设计与分析:动态规划 - TSP问题和0-1背包问题
c++·算法·动态规划
ward RINL42 分钟前
# GPT-5.6-sol vs GPT-5.5 新题实测:非弹性碰撞物理题和稳定路由算法
网络·gpt·算法
灯澜忆梦42 分钟前
【dp_1】爬楼梯 | 斐波那契数 | 第 N 个泰波那契数 | 三步问题
算法·golang
学究天人43 分钟前
数学公理体系大全:第四章 ZFC公理的形式化与构造演算
线性代数·数学建模·矩阵·动态规划·图论·抽象代数·拓扑学