LeetCode 354. Matryoshka envelope problems (the longest rise subsequence DP / binary search)

1. Topic

Given the width and height of some tags envelope, width and height in integer form (w, h) appears.
When another envelope width and height are than this envelope big time, you can put the envelope in another envelope, like Russian dolls same.

Please computing can have up to the number of envelopes can be composed of a set of "Matryoshka" envelope (which can put an envelope into another envelope inside).

Note:
No rotation envelope .

示例:
输入: envelopes = [[5,4],[6,4],[6,7],[2,3]]
输出: 3 
解释: 最多信封的个数为 3, 组合为: [2,3] => [5,4] => [6,7]

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/russian-doll-envelopes
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

2. Problem Solving

DP not write, optimal efficiency is writing binary search, DP written reference to the above link

class Solution {
public:
    int maxEnvelopes(vector<vector<int>>& envelopes) {
        sort(envelopes.begin(), envelopes.end(),[&](auto a, auto b){
        	if(a[1]==b[1])
        		return a[0] > b[0];//相等情况下,另一分量逆序
        	return a[1] < b[1];//【1】分量有序了
        });
        int i, idx=0, n = envelopes.size();
        vector<int> dp(n);
        for(i = 0; i < n; ++i)
        {
        	auto it = lower_bound(dp.begin(),dp.begin()+idx,envelopes[i][0]);
        	*it = envelopes[i][0];
        	if(it-dp.begin() == idx)
        		idx++;
        }
        return idx;
    }
};

412 ms 47.9 MB

Published 820 original articles · won praise 1791 · Views 410,000 +

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/105370146