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

朴素解法,先对信封按width从小到大排序。
再观察height找出最长升序序列。
动态规划的方程为:
dp[i] = dp[k] + 1, while k < i and ith height is larger than kth height.
算法复杂度 O(n^2)
最快的应该是O(nlogn),trick参考LIS算法

#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
using namespace std;

/**
 * @brief
 * dp[i] = dp[k] + 1, while k < i and i is larger than k
 */
class Solution {
public:

    static bool cmp(const pair<int, int> &a, const pair<int, int> &b) {
        return a.first <  b.first;
    }

   int maxEnvelopes(vector<pair<int, int>>& envelopes) {
       int N = envelopes.size();
       vector<int> dp(N, 1);
       int mx = (envelopes.size() == 0) ? 0 : 1;
       sort(envelopes.begin(), envelopes.end(), cmp);
       for(int i = 1, size = envelopes.size(); i < size; i++){
           for(int j = 0; j < i; j++){
               if (envelopes[i].first > envelopes[j].first && envelopes[i].second > envelopes[j].second) {
                   dp[i] = max(dp[i], dp[j] + 1);
                   mx = max(mx, dp[i]);
               }
           }
       }
       return mx;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,811评论 0 23
  • 那是生活的航行还没开始的时候,我哪里都没去过,只是一个原乡原土的小孩。 从天空飘浮的白云看下去,我在地球上一个叫浦...
    Graceland阅读 1,823评论 20 20
  • 你 我 一直未能合称我们 我们 离得很近 又很远 盯着一只飞走的气球 不自觉的握了握拳 手里却连那根断线都没有 我...
    Cat33阅读 285评论 0 1