Russian Doll Envelopes-leetcode
Topic:
You had 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 h Eight of the other envelope.
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]).
Make up for last week's homework.
And then picked a dynamic programming topic (a little bit of the end of this kind of problem)
Gives the length and width of a set of envelopes, requiring the maximum number of nested envelopes
After reading the topic there is a very natural idea, to nest of course is to choose a minimum, and then from small to large to try, so that the size of the envelope to sort, the size of the envelope has two properties, length and width, so sort to use the base sort.
The base order of two attribute values is convenient with pair (it happens that the data given by the topic is also this form), in the following code
Then there is the key link,
Use a two-dimensional array dp[n][2],dp[i][0] to denote the maximum number of nested quantities of the first envelope, without the first envelope, dp[i][1] indicates the maximum number of nesting for the first I envelope using the I envelope
Dp[i][0] = max (dp[i-1][0],dp[i-1][1]) this is obvious.
DP[I][1] You need to go through the front i-1 envelope to see if you can cover
class Solution {public:int maxenvelopes (vector< pair<int, int> >& Envelopes
{if (envelopes.size () = = 0) return 0;
Sort (Envelopes.begin (), Envelopes.end ());
vector< vector<int> > DP (envelopes.size () +1, vector<int> (2, 0));
Dp[0][0] = 0;
DP[0][1] = 1;
for (int i = 1; i < envelopes.size (); i++) {dp[i][0] = max (dp[i-1][0],dp[i-1][1]);
DP[I][1] = 1; for (int j = 0; J < i; J + +) {if (Envelopes[i].first > Envelopes[j].first && envelopes[i].se
Cond > Envelopes[j].second) {dp[i][1] = max (dp[i][1], dp[j][1]+1); This only needs to compare dp[i][1] and does not need to compare dp[i][0], because the value of dp[i][0] must be equal to some Dp[k][1],k<i}}} return
Max (Dp[envelopes.size () -1][0],dp[envelopes.size () -1][1]); }
};