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]).
1. DP O(n^2)
class Solution {
public:
int maxEnvelopes(vector<pair<int, int>>& envelopes) {
int N = envelopes.size();
int res = (N == 0) ? 0:1;
sort(envelopes.begin(), envelopes.end());
vector<int> dp(N,1);
for(int i = 0; i < N; 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);
}
}
res = max(res,dp[i]);
}
return res;
}
};
2. lower_bound O(nlogn)
class Solution {
public:
int maxEnvelopes(vector<pair<int, int>>& envelopes) {
sort(envelopes.begin(), envelopes.end(), [](pair<int, int> a, pair<int, int> b){
return a.first < b.first || (a.first == b.first && a.second > b.second);});
vector<int> dp;
for (auto e : envelopes)
{
auto iter = lower_bound(dp.begin(), dp.end(), e.second);
if (iter == dp.end())
dp.push_back(e.second);
else if (e.second < *iter)
*iter = e.second;
}
return dp.size();
}
};
第二个不太懂,为什么要使second逆序排列?
答:因为这样才能把第一位相同但第二位特别大的给替换掉。比如下面例子:(6,360)把(6,370)顶替掉,这样(7,380)能加入;同理(5,500)也会被后面更小的换掉。
还是这个解释比较好:
- Sort the array. Ascend on width and descend on height if width are same.
- Find the longest increasing subsequence based on height.
- Since the width is increasing, we only need to consider height.
- [3, 4] cannot contains [3, 3], so we need to put [3, 4] before [3, 3] when sorting otherwise it will be counted as an increasing number if the order is [3, 3], [3, 4]
3. binary-search
class Solution {
public:
int maxEnvelopes(vector<pair<int, int>>& envelopes) {
vector<int> dp;
sort(envelopes.begin(), envelopes.end(), [](const pair<int, int> &a, const pair<int, int> &b){
if (a.first == b.first) return a.second > b.second;
return a.first < b.first;
});
for (int i = 0; i < envelopes.size(); ++i) {
int left = 0, right = dp.size(), t= envelopes[i].second;
while (left < right) {
int mid = left + (right - left) / 2;
if (dp[mid] < t) left = mid + 1;
else right = mid;
}
if (right >= dp.size()) dp.push_back(t);
else dp[right] = t;
}
return dp.size();
}
};
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
例子:
int main(int argc, const char * argv[]) {
vector<pair<int, int>>envelopes={{2,100},{3,200},{4,300},{5,500},{5,400},{5,250},{6,370},{6,360},{7,380}};
int res = maxEnvelopes2(envelopes);
cout<<res<<endl;
return 0;
}
结果:
5