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)
Note:
Rotation is not allowed.
Example:
Input: [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3
([2,3] => [5,4] => [6,7]).
这道题可以使用动态规划来处理。转移条件是:
if (envelopes[i][0] > envelopes[j][0] && envelopes[i][1] > envelopes[j][1]) {
dp[i] = max(dp[i], dp[j] + 1);
}
也就是如果一个envelope包含另一个envelope,那就把大的envelope+1.
注意,我们的程序从左往右遍历,所以我们将小(面积小)的信封放在左边。
class Solution {
public:
int maxEnvelopes(vector<vector<int>>& envelopes) {
if (envelopes.empty()) return 0;
sort(envelopes.begin(), envelopes.end(), [](vector<int> a, vector<int> b)->bool {return a[0] * a[1] < b[0] * b[1]; });
vector<int> dp(envelopes.size(), 1);
int ans = 1;
for (int i = 0; i < envelopes.size(); i++) {
for (int j = 0; j < i; j++) {
if (envelopes[i][0] > envelopes[j][0] && envelopes[i][1] > envelopes[j][1]) {
dp[i] = max(dp[i], dp[j] + 1);
ans = max(ans, dp[i]);
}
}
}
return ans;
}
};