題目:
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.csdn.net/caoyan_12727/article/details/52904132
如果一個信封i要能裝進另一個信封j,那麼i的長要大於j的長且i的寬要大於j的寬,則我們可以先對每個信封的長和寬進行升序排序,然後記錄每個信封當前可以裝下的最大信封
數!!!!!