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的LIS,不过学到了nlogn的算法了 还不错。

这个是普通的O(n^2)的dp解法。

 bool cmp(pair<int, int>&a,pair<int, int>&b){
    if(a.first!=b.first)return a.first<b.first;
    return a.second>b.second;
}
class Solution {
public:
    int maxEnvelopes(vector<pair<int, int>>& envelopes) {
        if(envelopes.empty())return 0;
        sort(envelopes.begin(),envelopes.end(),cmp);
        int ans=-1,n=envelopes.size();
        int dp[n];
        for(int i=0;i<n;i++){
            dp[i]=1;
            for(int j=0;j<i;j++){
                if(envelopes[j].first!=envelopes[i].first&&envelopes[j].second<envelopes[i].second&&dp[j]+1>dp[i]){
                   dp[i]=dp[j]+1;
                }
            }
            ans=max(ans,dp[i]);
        }
        return ans;
    }
};

O(nlogn)的思想:

开一个栈,将a[0]入栈,每次取栈顶元素top和读到的元素ai做比较,如果a[i]> top 则将a[i]入栈;如果a[i]<= top则二分查找栈中的比a[i]大的第1个数,并用a[i]替换它。 最长序列长度即为栈的大小top。

这是很好理解的,对于x和y,如果x < y且stack[y] > stack[x],用stack[x]替换stack[y],此时的最长序列长度没有改变,但序列继续变长的''潜力''增大了。
举例:原序列为1,5,8,3,6,7
开始1,5,8相继入栈,此时读到3,用3替换5,得到1,3,8;
再读6,用6替换8,得到1,3,6;
再读7,得到最终栈为1,3,6,7。最长递增子序列为长度4。

 bool cmp(pair<int, int>&a,pair<int, int>&b){
    if(a.first!=b.first)return a.first<b.first;
    return a.second>b.second;
}
class Solution {
public:
    int maxEnvelopes(vector<pair<int, int>>& envelopes) {
        if(envelopes.empty())return 0;
        sort(envelopes.begin(),envelopes.end(),cmp);
        vector<int>dp;
        for (int i = 0; i < envelopes.size(); ++i) {
            auto it = lower_bound(dp.begin(), dp.end(), envelopes[i].second);
            if (it == dp.end()) dp.push_back(envelopes[i].second);
            else *it = envelopes[i].second;
        }
        return dp.size();
    }
};

 

posted @ 2017-02-23 18:13  Tsunami_lj  阅读(187)  评论(0编辑  收藏  举报