LeetCode354. Russian Doll Envelopes——动态规划

文章目录

一、题目

You are given a 2D array of integers envelopes where envelopes[i] = [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

envelopes[i].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;
    }
};
相关推荐
孟大本事要学习23 分钟前
算法第15天:继续二叉树|前序递归+回溯与前序递归的场景总结、最大二叉树、合并二叉树、二叉搜索树中的搜索、验证二叉搜索树
算法
GalaxyPokemon36 分钟前
LeetCode - 76. 最小覆盖子串
运维·服务器·数据结构·算法·leetcode
嵌入式@秋刀鱼40 分钟前
《 第三章-招式初成》 C++修炼生涯笔记(基础篇)程序流程结构
linux·开发语言·数据结构·c++·笔记·visual studio code
HaiQinyanAN1 小时前
【学习笔记】重载和重写的注意事项
c++·笔记·学习
手握风云-1 小时前
动态规划算法的欢乐密码(二):路径问题
算法·动态规划
小马爱打代码1 小时前
数据结构 - Java 队列
java·数据结构
西北大程序猿2 小时前
服务器代码知识点补充
服务器·开发语言·网络·c++·网络协议
Raven100862 小时前
L1G2-OpenCompass 评测书生大模型实践
算法
NAGNIP2 小时前
RAG信息检索-如何让模型找到‘对的知识’
算法
大大大大小小2 小时前
26-数据结构-线性表2
java·数据结构·restful