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,900評論 0 23
  • 那是生活的航行還沒開始的時候,我哪里都沒去過,只是一個原鄉原土的小孩。 從天空飄浮的白云看下去,我在地球上一個叫浦...
    Graceland閱讀 1,824評論 20 20
  • 你 我 一直未能合稱我們 我們 離得很近 又很遠 盯著一只飛走的氣球 不自覺的握了握拳 手里卻連那根斷線都沒有 我...
    Cat33閱讀 286評論 0 1