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;
    }
};
相关推荐
GreenTea5 小时前
深度解读 Anthropic 多智能体报告:更强的模型 ≠ 更好的协调
前端·后端·算法
码匠许师傅5 小时前
【C++ 面试真题】聊聊 C++ 的移动语义与右值引用
java·c++·面试
fqq36 小时前
力扣刷题前置Java语法
算法·leetcode·职场和发展
小小龙学IT6 小时前
DuckDB 深度实战:用 C++ 在进程内跑一个「分析型数据库」
数据库·c++
知无不研8 小时前
lambda表达式的使用(3)
开发语言·c++·lambda
半夏微凉半夏殇8 小时前
x11与weston对比,优先选哪个
leetcode·均值算法·eclipse
2501_906565128 小时前
数学之美探究
算法
oier_Asad.Chen8 小时前
【洛谷题解/AcWing题解/OI学习笔记】洛谷P2868【USACO07DEC】Sightseeing Cows G(01分数规划求最大比率)
算法·图论·spfa·二分·负环
C++ 老炮儿的技术栈9 小时前
基于Qt实现轻量化本地音乐播放器
开发语言·c++·qt·c·播放器·音乐
leisoo809710 小时前
财报数据怎么排雷本地化Python构建财务异常预警系统
人工智能·python·算法