[Leetcode] 354. Russian Doll Envelopes 解题报告

本文介绍了一种解决俄罗斯套娃信封问题的方法,通过将问题转化为寻找最长递增子序列,给出了高效的二分查找解决方案。通过对示例的详细分析,展示了如何利用这种技巧求解最大数量的可嵌套信封。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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)

Example:
Given envelopes = [[5,4],[6,4],[6,7],[2,3]], the maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).

思路

只要巧妙地变换一下,就是一道最长递增子序列的题目。我们用题目中给出的例子进行分析。如果在x维度上升序排列,而在x相同的情况下,在y维度上降序排列,那么上例的排序结果就是:[[2,3], [5,4], [6,7], [6,4]]。我们发现,只要在y维度上找到最长递增子序列,就对应了本题的答案。为什么呢?因为如果在y维度上如果已经递增了,那么在x维度上必然是递增的,用反证法来证明:对于有序区间[s1,e1]和[s2,e2](意味着s1 <= s2),如果e1 < e2,假设s1 == s2,那么区间[s2,e2]必然在排序的时候会排在[s1,e1]之前,与有序前区间这一前提矛盾。所以必然s1 < s2。

从理论上证明正确性之后,我们考虑最长子序列问题的两个经典解法:1)动态规划;2)二分查找。前者的时间复杂度是O(n^2),后者的时间复杂度是O(nlogn)。我们这里实现的是二分查找。Leetcode上就有一道关于最长递增子序列的题目,请参考我的另外一篇博客:http://blog.youkuaiyun.com/magicbean2/article/details/75242590,里面有更详细的分析和解答。

代码

class Solution {
public:
    int maxEnvelopes(vector<pair<int, int>>& envelopes) {
        if(envelopes.size() == 0) {
            return 0;
        }
        sort(envelopes.begin(), envelopes.end(), PairComp);
        vector<int> ans;
        for(auto val : envelopes) {
            if(ans.empty() || val.second > ans.back()) {    // ans.back() can be put into val
                ans.push_back(val.second);
            }
            else {          // val.second <= ans.back() means a better (smaller) envelope found
                auto it = lower_bound(ans.begin(), ans.end(), val.second);
                *it = val.second;
            }
        }
        return ans.size();
    }
private:
    struct PairCompare {
        bool operator() (const pair<int, int>& a, const pair<int, int>& b) const {
            if(a.first < b.first)       return true;
            else if(a.first > b.first)  return false;
            else                        return a.second > b.second;
        }
    } PairComp;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值