LeetCode #354. Russian Doll Envelopes

本文探讨了俄罗斯套娃信封问题,这是一个经典的计算机科学问题,涉及到如何将多个具有不同宽度和高度的信封按照一定规则进行嵌套,以达到最大数量的嵌套。文章通过一个具体的例子解释了问题,并提供了一种解决方案,使用了排序和动态规划的思想。

题目描述:

You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.

What is the maximum number of envelopes can you Russian doll? (put one inside other)

Note:
Rotation is not allowed.

Example:

Input: [[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]).
class Solution {
public:
    static bool comp(const vector<int>& a, const vector<int>& b)
    {
        // 先按宽度从小到大排序,宽度相同时按照高度从大到小排序
        // 因为宽度相同时不能重叠,将高度较大的放在前面避免这种情况
        if(a[0]<b[0]) return true;
        else if(a[0]==b[0]&&a[1]>b[1]) return true;
        else return false;
    }
    
    int maxEnvelopes(vector<vector<int>>& envelopes) {
        sort(envelopes.begin(),envelopes.end(),comp);
        vector<int> dp;
        for(vector<int>& envelope:envelopes)
        {
            auto it=lower_bound(dp.begin(),dp.end(),envelope[1]);
            if(it==dp.end()) dp.push_back(envelope[1]);
            else *it=envelope[1];
        }
        return dp.size();
    }
};

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值