LeetCode 354. Russian Doll Envelopes 俄罗斯套娃信封问题

9 篇文章 0 订阅
4 篇文章 0 订阅

LeetCode 354. Russian Doll Envelopes 俄罗斯套娃信封问题

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.

示例:

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

解答

遇见这种题一上来应该先排一下序,先按照套娃的宽度从小到大排序,如果宽度相同就按照高度从小到大排序。

这样就可以用DP的方法来求解了,DP数组中值最大的就是解(解法1)。

但是这道题还有一道更巧妙的解法:先按照套娃的宽度从小到大排序,如果宽度相同就按照高度从大到小排序。

然后这道题就转换称为高度的最长上升子序列问题(点击查看详解),最长上升子序列的长度就是解(解法2)。

代码

解法1
class Solution {
public:
    int maxEnvelopes(vector<pair<int, int>>& envelopes) {
        if (envelopes.size() == 0) return 0;
        auto n = envelopes.size();
        sort(envelopes.begin(), envelopes.end());
        vector<int> dp(n, 1);
        for (int i = 0; i < n; ++i)
            for (int j = 0; j < i; ++j)
                if (envelopes[j].first < envelopes[i].first && envelopes[j].second < envelopes[i].second)
                    dp[i]  = max(dp[i] , dp[j] + 1);
        return *max_element(dp.begin(), dp.end());
    }
};
解法2
class Solution {
public:
    int maxEnvelopes(vector<pair<int, int>>& envelopes) {
        if (envelopes.size() == 0) return 0;
        auto n = envelopes.size();
        vector<int> res;  
        sort(envelopes.begin(), envelopes.end(), [](pair<int, int> a, pair<int, int> b) {
            if (a.first == b.first) return a.second > b.second;
            return a.first < b.first;
        });
        
        for (auto v : envelopes) {
            auto iter = lower_bound(res.begin(), res.end(), v.second);
            if (iter == res.end()) 
                res.push_back(v.second);
            else
                *iter = v.second;
        }
        return res.size();

    }


    
};
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值