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;
}
};