动态规划 hard LeetCode 354. Russian Doll Envelopes

来源:互联网 发布:全国高校校花知乎 编辑:程序博客网 时间:2024/06/01 08:41

这周依旧是动态规划,老师说动态规划的内容很多,有很多变种,所以讲了很久,前几天看到一篇文章说动态规划不是一种算法而是一种思想,觉得挺有道理的,毕竟它不像其他算法那样有一个固定的方法,但是某种程度上来说也是有的,嗯,进入正题吧,不纠结这个问题了。下面看一看这周的题吧,难度为hard,题目如下:

--------------------------题目-----------------------------

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 is3 ([2,3] => [5,4] => [6,7]).

--------------------------题解------------------------------

题目很好理解,用俄罗斯套娃来理解,当一个信封的长宽都大于另一个信封时,另一个信封就可以装进这一个信封中,很符合生活常识吧,需要严格的大于。我想这里应该是忽略厚度吧,要不然最外面的信封会被撑爆的吧。动态规划的思想就是我只需要知道上一个状态的结果就行了,不需要知道上一个状态具体是什么状态,放到这道题的话就是我只需要知道那个长宽都小于我手上这个信封的信封装了多少个信封而不需要知道具体都有那些信封,具体看代码的注释吧。

#include <iostream>#include <vector>#include <algorithm>#include <memory.h>using namespace std;class Solution {public:static bool cmp1(pair<int,int> a,pair<int,int> b){return a.first<b.first;}static bool cmp2(pair<int,int> a,pair<int,int> b){return a.second<b.second;}    int maxEnvelopes(vector<pair<int, int> >& envelopes) {        sort(envelopes.begin(),envelopes.end(),cmp1);        sort(envelopes.begin(),envelopes.end(),cmp2);//桶排序        int en[10000];//不能像传统那样用长宽作为两个维度,感觉会爆内存,题目也没给数据范围        memset(en,0,sizeof(en));        int l=envelopes.size();        int ans=0;        for(int i=0;i<l;i++)        {        int w=envelopes[i].first;        int h=envelopes[i].second;        en[i]=1;        for(int j=0;j<i;j++)        {        int nw=envelopes[j].first;        int nh=envelopes[j].second;        if(w>nw&&h>nh)        en[i]=max(en[i],en[j]+1);//状态转移方程,只有可能装下当前信封前面的信封,所以遍历一下前面的这些信封,找到使当前状态最大的结果}ans=max(ans,en[i]);}    return ans;}    };题还是比较简单的,之前按照两个维度写过不了,后来观察了一下发现两个维度的话前后状态与这两个维度并没有什么联系,所以就没必要用两个维度了,就用向量下标就好了。---------------------分割线----------------------see you next illusion


0 0
原创粉丝点击