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;
    }
};
相关推荐
爱喝热水的呀哈喽9 分钟前
非线性1无修
算法
GG不是gg19 分钟前
数据结构:二叉树一文详解
数据结构·青少年编程
hjjdebug28 分钟前
c/c++数据类型转换.
c语言·c++·数据类型变换
熬夜学编程的小王32 分钟前
【C++进阶篇】C++容器完全指南:掌握set和map的使用,提升编码效率
c++·set·map
花火QWQ33 分钟前
图论模板(部分)
c语言·数据结构·c++·算法·图论
Pacify_The_North1 小时前
【进程控制二】进程替换和bash解释器
linux·c语言·开发语言·算法·ubuntu·centos·bash
superior tigre1 小时前
C++学习:六个月从基础到就业——C++20:协程(Coroutines)
c++·学习·c++20
superior tigre1 小时前
C++学习:六个月从基础到就业——C++20:概念(Concepts)
c++·学习·c++20
轮到我狗叫了1 小时前
力扣310.最小高度树(拓扑排序,无向图),力扣.加油站力扣.矩阵置零力扣.二叉树中的最大路径和
算法·leetcode·职场和发展
埃菲尔铁塔_CV算法1 小时前
深度学习驱动下的目标检测技术:原理、算法与应用创新(二)
深度学习·算法·目标检测