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;
    }
};
相关推荐
bikong721 小时前
Qt/C++,windows多进程demo
c++·windows·qt
努力学习的小廉21 小时前
我爱学算法之—— 位运算(上)
c++·算法
Chance_to_win21 小时前
数据结构之顺序表
数据结构
ゞ 正在缓冲99%…21 小时前
leetcode35.搜索插入位置
java·算法·leetcode·二分查找
lifallen1 天前
字节跳动Redis变种Abase:无主多写架构如何解决高可用难题
数据结构·redis·分布式·算法·缓存
青草地溪水旁1 天前
设计模式(C++)详解—原型模式(1)
c++·设计模式·原型模式
feifeigo1231 天前
星座SAR动目标检测(GMTI)
人工智能·算法·目标跟踪
怀旧,1 天前
【C++】20. unordered_set和unordered_map
开发语言·c++
WWZZ20251 天前
视觉SLAM第10讲:后端2(滑动窗口与位子图优化)
c++·人工智能·后端·算法·ubuntu·机器人·自动驾驶
alibli1 天前
一文学会CMakeLists.txt: CMake现代C++跨平台工程化实战
开发语言·c++·系统架构