题目:
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]).
Subscribe to see which companies asked this question
Hide Tags Binary Search Dynamic Programming
Hide Similar Problems (M) Longest Increasing Subsequence
源码:
class Solution {
public:
int maxEnvelopes(vector<pair<int, int>>& envelopes) {
int size = envelopes.size();
if (size == 0)return 0;
if (size == 1)return 1;
multimap<int, pair<int, int>>info;
int sum = 0;
for (int i = 0; i < size; i++){
sum = envelopes[i].first + envelopes[i].second;
info.insert(make_pair(sum, envelopes[i]));//按和进行排序
}
vector<int>re(info.size(), 0);
vector<pair<int, int>>da;
for (map<int, pair<int, int>>::iterator i = info.begin(); i != info.end(); i++)da.push_back((*i).second);
re[0] = 1;
size = da.size();
int total_max = 1;
for (int i = 1; i < size; i++){//寻找每一个位置
int tmp_value = 0;
int max = 0;
for (int j = i - 1; j >= 0; j--){
if (i<size&&j>=0&&da[i].first>da[j].first&&da[i].second>da[j].second){
tmp_value = re[j] + 1;
if (tmp_value > max)max = tmp_value;
}
}
if (max == 0)re[i] = 1;
else re[i] = max;
if (re[i] >= total_max)total_max = re[i];
}
return total_max;
}
};
Submission Result: Accepted More Details
Share your acceptance!
分析:这道的思路与leetcode-368Largest Divisible Subset的思路完全一样,详情请参照博客:http://blog.youkuaiyun.com/caoyan_12727/article/details/52904132
如果一个信封i要能装进另一个信封j,那么i的长要大于j的长且i的宽要大于j的宽,则我们可以先对每个信封的长和宽进行升序排序,然后记录每个信封当前可以装下的最大信封
数!!!!!