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]).
This is greedy algorithm.
bool sorter(pair<int, int>& a, pair<int, int>& b) {
return a.first <= b.first;
}
int maxEnvelops(vector<pair<int, int> >& envelopes) {
if(envelopes.size() <= 1) return envelopes.size();
sort(envelopes.begin(), envelopes.end(), sorter);
// max increasing length.
int n = envelopes.size();
vector<int> dp(n + 1, 1);
for(int i = 1; i <= envelopes.size(); ++i) {
for(int j = 0; j < i; ++j) {
if(envelopes[j].second >= envelopes[i].second) {
dp[i] = max(dp[i], dp[j] + 1);
}
}
}
int maxValue = 0;
for(int i = 0; i <= n; ++i) {
maxValue = max(dp[i], maxValue);
}
return maxValue;
}
int main(void) {
vector<pair<int, int> > inputs{{5, 4}, {6, 4}, {6, 7}, {2, 3}};
cout << maxEnvelops(inputs) << endl;
}
本文探讨了一种基于贪心算法解决俄罗斯套娃信封问题的方法。给定一系列宽度和高度不同的信封,目标是找出能互相套叠的最大数量。通过排序和动态规划算法,实现对信封的有效匹配。
525

被折叠的 条评论
为什么被折叠?



