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;
    }
};
相关推荐
千里镜宵烛3 分钟前
深入理解 Linux 线程:从概念到虚拟地址空间的全面解析
开发语言·c++·操作系统·线程
欧哈东哥7 分钟前
【C++】标准库中用于组合多个值的数据结构pair、tuple、array...
java·数据结构·c++
来自天蝎座的孙孙43 分钟前
洛谷P1595讲解(加强版)+错排讲解
python·算法
GawynKing1 小时前
图论(5)最小生成树算法
算法·图论·最小生成树
试剂界的爱马仕1 小时前
胶质母细胞瘤对化疗的敏感性由磷脂酰肌醇3-激酶β选择性调控
人工智能·科技·算法·机器学习·ai写作
打不了嗝 ᥬ᭄1 小时前
Linux 信号
linux·开发语言·c++·算法
张子夜 iiii2 小时前
机器学习算法系列专栏:主成分分析(PCA)降维算法(初学者)
人工智能·python·算法·机器学习
ZLRRLZ2 小时前
【C++】C++11
开发语言·c++
一匹电信狗2 小时前
【C++】异常详解(万字解读)
服务器·c++·算法·leetcode·小程序·stl·visual studio
sp422 小时前
白话 LRU 缓存及链表的数据结构讲解(二)
算法