354. Russian Doll Envelopes

来源:互联网 发布:烟雾视频软件 编辑:程序博客网 时间:2024/05/16 17:25

Description:

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


[cpp] view plain copy
  1. #include <iostream>  
  2. #include <vector>  
  3. #include <algorithm>  
  4. #include <memory.h>  
  5. using namespace std;  
  6.   
  7. class Solution {  
  8. public:  
  9.     static bool cmp1(pair<int,int> a,pair<int,int> b)  
  10.     {  
  11.         return a.first<b.first;  
  12.     }  
  13.     static bool cmp2(pair<int,int> a,pair<int,int> b)  
  14.     {  
  15.         return a.second<b.second;  
  16.     }  
  17.     int maxEnvelopes(vector<pair<intint> >& envelopes) {  
  18.         sort(envelopes.begin(),envelopes.end(),cmp1);  
  19.         sort(envelopes.begin(),envelopes.end(),cmp2);
  20.         int en[10000];
  21.         memset(en,0,sizeof(en));  
  22.         int l=envelopes.size();  
  23.         int ans=0;  
  24.         for(int i=0;i<l;i++)  
  25.         {  
  26.             int w=envelopes[i].first;  
  27.             int h=envelopes[i].second;  
  28.             en[i]=1;  
  29.             for(int j=0;j<i;j++)  
  30.             {  
  31.                 int nw=envelopes[j].first;  
  32.                 int nh=envelopes[j].second;  
  33.                 if(w>nw&&h>nh)  
  34.                 en[i]=max(en[i],en[j]+1);
  35.             }  
  36.             ans=max(ans,en[i]);  
  37.         }  
  38.         return ans;  
  39.     }  
  40.       
  41. };