Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

An intuitive DP - should be 'medium'.

class Solution {
public:
    int maxEnvelopes(vector<pair<int, int>>& envelopes) {
        int n = envelopes.size();
        if (!n) return 0;
        if (n == 1) return 1;
        
        //  Sort by Area
        sort(envelopes.begin(), envelopes.end(), [](const pair<int, int> &e1, const pair<int, int> &e2){
            return (e1.first *e1.second) < (e2.first *e2.second);
        });
        
        int ret = 1;
        vector<int> dp(n, 1);
        for(int i = 1; i < n; i ++)
        {
            pair<int, int> &ce = envelopes[i];
            for(int j = 0; j < i; j ++)
            {
                pair<int, int> &cp = envelopes[j];
                if((ce.first > cp.first && ce.second > cp.second) 
                    )
                {
                    dp[i] = max(dp[i], dp[j] + 1);
                }
                ret = max(ret, dp[i]);
            }
        }
        
        return ret;
    }
};
posted on 2016-06-07 06:20  Tonix  阅读(281)  评论(0编辑  收藏  举报