包信封问题 以及 最长有序子序列问题

https://leetcode.com/problems/russian-doll-envelopes/?tab=Description

包信封问题,可以转化成最长有序子序列问题,见下面的分析:

https://discuss.leetcode.com/topic/47469/java-nlogn-solution-with-explanation/2

尤其是其中第二部分C++的解法。

 

而最长有序子序列问题:

https://leetcode.com/problems/longest-increasing-subsequence/?tab=Description

 

非常经典,是可以有O(nlgn)的解法的:

解法在上面那道题目的解法里面也有体现。实现如下:

 

class Solution {
public:
    static bool cmp_first(const pair<int, int>& i, const pair<int, int>& j) {
        if (i.first == j.first)
            return i.second > j.second;
        return i.first < j.first;
    }
    int maxEnvelopes(vector<pair<int, int>>& envelopes) {
        vector<int> candidates;
        sort(envelopes.begin(), envelopes.end(), cmp_first);
        vector<int> dp;
        for (int i = 0; i < envelopes.size(); ++i) {
            auto itr = lower_bound(dp.begin(), dp.end(), envelopes[i].second);
            if (itr == dp.end()) {
                dp.push_back(envelopes[i].second);
            } else {
                *itr = envelopes[i].second;
            }
        }
        return dp.size();
  }
};

其中用到了 lower_bound,这个函数的含义,找出本身作为lower_bound的位置,也就是第一个大于等于输入数的位置。

 

posted @ 2017-02-26 01:17  blcblc  阅读(243)  评论(0编辑  收藏  举报