leetcode 354. Russian Doll Envelopes

本文介绍了一种解决俄罗斯套娃信封问题的方法,该问题实际上为最长上升子序列(LIS)问题的一种变形。文章详细阐述了通过固定一维并求另一维的LIS来解决问题的策略,并给出了具体的C++代码实现。

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]).

其实这道题目就是最长上升子序列(LIS)的改编。
思路:先固定一维,然后在另一维进行求LIS操作。注意在固定一维的时候,可能存在(12,6)(12,5)(1,3)怎么排序的问题,对于这种情况,要把第二维大的排在前面如(1,3)(12,6)(12,5)。因为只有这样,对于第二维求LIS才能保证正确性(就是贪心嘛,第一维相同那么我就取第二维比较大的那个,因为只有这样才能让小的有机会替换,回想LIS中的d序列...)。

class Solution {
public:
    int maxEnvelopes(vector<pair<int, int>>& envelopes) {
        int n = envelopes.size();
        if (n == 0) return 0;
        if (n == 1) return 1;
        auto cmp = [](pair<int, int> a, pair<int, int> b)   
        { return a.first == b.first ? a.second > b.second : a.first < b.first; };  
        sort(envelopes.begin(), envelopes.end(), cmp);

        vector<int> p(n+1);
        p[0] = envelopes[0].second;
        int len = 0;
        
        for (int i = 1; i < n; ++i) {
            if (envelopes[i].second > p[len]) {
                ++len;
                p[len] = envelopes[i].second;
            } else if (envelopes[i].second < p[len]) {
                int pos = lower_bound(p.begin(), p.begin()+len, envelopes[i].second) - p.begin();
                p[pos] = envelopes[i].second;
            }
        }
        return len + 1;
    }
};

转载于:https://www.cnblogs.com/pk28/p/7806962.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值