Leetcode 354. Russian Doll Envelopes
Problem:
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)
Note:
Rotation is not allowed.
Example:
Input: [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3
([2,3] => [5,4] => [6,7]).
Solution:
俄罗斯套娃问题,LCS问题的变种。当然可以用动态规划解答,时间复杂度为O(n2),这种方法就不多阐述了,还有一种O(nlogn)的解法,和LCS解法非常类似,首先根据第一个元素对数组排序,维护一个数组dp,dp[i]记录了长度为i+1的套娃的最小的高度,注意长度weight在dp数组中未必是递增的,但高度必然是递增的,为什么呢?因为我们事先根据长度排序过了,所以我们后面找到的套娃必然是长度大于等于dp数组中的任何一个套娃的长度的。因此我们只需要保证高度height递增就行了,剩下的就和LCS问题完全一样了,用二分法找到第一个高度比当前套娃高度大的套娃将其替换即可。
Code:
1 class Solution { 2 public: 3 struct mycmp{ 4 bool operator()(pair<int,int> &p1,pair<int,int> &p2){ 5 if(p1.first == p2.first) 6 return p1.second > p2.second; 7 return p1.first < p2.first; 8 } 9 }cmp; 10 int maxEnvelopes(vector<pair<int, int>>& envelopes) { 11 if(envelopes.size() == 0) return 0; 12 sort(envelopes.begin(),envelopes.end(),cmp); 13 vector<pair<int,int>> dp; 14 dp.push_back(envelopes[0]); 15 for(int i = 1;i != envelopes.size();++i){ 16 if(envelopes[i].second > dp.back().second && envelopes[i].first > dp.back().first){ 17 dp.push_back(envelopes[i]); 18 continue; 19 } 20 int start = 0; 21 int end = dp.size()-1; 22 while(start < end){ 23 int pivot = start + (end-start)/2; 24 if(dp[pivot].second < envelopes[i].second) 25 start = pivot+1; 26 else 27 end = pivot; 28 } 29 dp[start] = envelopes[i]; 30 } 31 return dp.size(); 32 } 33 };