题目:
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]).
思路:
只要巧妙地变换一下,就是一道最长递增子序列的题目。我们用题目中给出的例子进行分析。如果在x维度上升序排列,而在x相同的情况下,在y维度上降序排列,那么上例的排序结果就是:[[2,3], [5,4], [6,7], [6,4]]。我们发现,只要在y维度上找到最长递增子序列,就对应了本题的答案。为什么呢?因为如果在y维度上如果已经递增了,那么在x维度上必然是递增的,用反证法来证明:对于有序区间[s1,e1]和[s2,e2](意味着s1 <= s2),如果e1 < e2,假设s1 == s2,那么区间[s2,e2]必然在排序的时候会排在[s1,e1]之前,与有序前区间这一前提矛盾。所以必然s1 < s2。
从理论上证明正确性之后,我们考虑最长子序列问题的两个经典解法:1)动态规划;2)二分查找。前者的时间复杂度是O(n^2),后者的时间复杂度是O(nlogn)。我们这里实现的是二分查找。Leetcode上就有一道关于最长递增子序列的题目,请参考我的另外一篇博客:http://blog.csdn.net/magicbean2/article/details/75242590,里面有更详细的分析和解答。
代码:
class Solution {
public:
int maxEnvelopes(vector<pair<int, int>>& envelopes) {
if(envelopes.size() == 0) {
return 0;
}
sort(envelopes.begin(), envelopes.end(), PairComp);
vector<int> ans;
for(auto val : envelopes) {
if(ans.empty() || val.second > ans.back()) { // ans.back() can be put into val
ans.push_back(val.second);
}
else { // val.second <= ans.back() means a better (smaller) envelope found
auto it = lower_bound(ans.begin(), ans.end(), val.second);
*it = val.second;
}
}
return ans.size();
}
private:
struct PairCompare {
bool operator() (const pair<int, int>& a, const pair<int, int>& b) const {
if(a.first < b.first) return true;
else if(a.first > b.first) return false;
else return a.second > b.second;
}
} PairComp;
};