二分+动态规划(最长上升子序列) 354. 俄罗斯套娃信封问题

44 篇文章 0 订阅
20 篇文章 0 订阅
解决354题俄罗斯套娃信封问题,通过排序和动态规划的方法,找到最多能组成的套娃信封数量。采用宽度降序、高度升序排序,利用二分查找与最长上升子序列思想,实现O(N^2)的时间复杂度解决方案。示例显示最多可以有3个信封相互套娃。
摘要由CSDN通过智能技术生成

354. 俄罗斯套娃信封问题

给定一些标记了宽度和高度的信封,宽度和高度以整数对形式 (w, h) 出现。当另一个信封的宽度和高度都比这个信封大的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。

请计算最多能有多少个信封能组成一组“俄罗斯套娃”信封(即可以把一个信封放到另一个信封里面)。

说明:
不允许旋转信封。

示例:

输入: envelopes = [[5,4],[6,4],[6,7],[2,3]]
输出: 3 

解释: 最多信封的个数为 3, 组合为: [2,3] => [5,4] => [6,7]。

排序+dp O(N^2)

class Solution {
private:
    vector<int> dp;
    static bool cmp(vector<int> a, vector<int> b){
        if(a[0]!=b[0]) return a[0]<b[0];
        return a[1]<b[1];
    }
public:
    int maxEnvelopes(vector<vector<int>>& envelopes) {
        int n= envelopes.size();
        sort(envelopes.begin(),envelopes.end(),cmp);
        dp.resize(n,1);  //以i结尾的信封,可以套多少
        int res=0;
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<i;j++){
                if(envelopes[i][0]>envelopes[j][0]&&envelopes[i][1]>envelopes[j][1])
                    dp[i]=max(dp[i],dp[j]+1);
            }
            res=max(res,dp[i]);
        }
        return res;
    }
};

注意点
class中设定cmp函数,需要设为static函数;
因为cmp函数中无this对象!

二分+最长上升子序列

将信封按高度升序排,再按宽度降序排列;
寻找宽度的最长上升子序列,即为最长的套娃数量;

cmp+二分

class Solution {
private:
vector<int> dp;
static bool cmp(vector<int>& a, vector<int>& b){
        if(a[0]!=b[0]) return a[0]<b[0];
        return a[1]>b[1];
    }
public:
    int maxEnvelopes(vector<vector<int>>& envelopes) {
        int n= envelopes.size();
        sort(envelopes.begin(),envelopes.end(),cmp);
        dp.resize(n,1);  //以i结尾的信封,可以套多少
        int end=0;
        for(auto t:envelopes){
            int left=0;
            int right=end;
            while(left<right){
                int mid=left+(right-left)/2;
                if(dp[mid]<t[1]) left=mid+1;
                else right=mid;
            }
            dp[left]=t[1];
            if(left==end) end++;
        }
        return end;
    }
};

lower_bound+sort

class Solution {
private:
vector<int> dp;
public:
    int maxEnvelopes(vector<vector<int>>& envelopes) {
        int n= envelopes.size();
        sort(envelopes.begin(),envelopes.end(),[](vector<int>& a, vector<int>& b){if(a[0]!=b[0]) return a[0]<b[0];return a[1]>b[1];});
        
        for(auto t:envelopes){
            auto iter=lower_bound(dp.begin(),dp.end(),t[1]);
            if(iter==dp.end()) dp.push_back(t[1]);
            else dp[iter-dp.begin()]=t[1];
        }
        return dp.size();
    }
};

注意点
排序传引用&,时间快几倍

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值