You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope.
One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope’s width and height.
Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).
Note: You cannot rotate an envelope.
Example 1:
Input: envelopes = [[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]).
Example 2:
Input: envelopes = [[1,1],[1,1],[1,1]]
Output: 1
Constraints:
1 <= envelopes.length <= 5000
envelopes[i].length == 2
1 <= wi, hi <= 104
相关标签:数组 二分查找 动态规划 排序
代码:这道题j就是排序+LIS,下面代码没有用二分查找,用的是结构体+排序。
代码:
#include <bits/stdc++.h>
struct node{
int w;
int h;
node(){
w=0;
h=0;
}
}arr[6500];
bool cmp(node a, node b){
if(a.w != b.w){
return a.w < b.w;
}
return a.h > b.h;
}
class Solution {
public:
int maxEnvelopes(vector<vector<int>>& envelopes) {
int len = envelopes.size();
for(int i=0; i<len; i++){
arr[i].w = envelopes[i][0];
arr[i].h = envelopes[i][1];
}
sort(arr,arr+len,cmp);
// for(int i=0; i<len; i++){
// cout<<arr[i].w<<" "<<arr[i].h<<endl;
// }
int dp[len];
int ans = 1;
memset(dp,0,sizeof(dp));
dp[0] = 1;
for(int i=1; i<len; i++){
dp[i] = 1;
for(int j=0; j<=i-1; j++){
if(arr[j].w<arr[i].w && arr[j].h<arr[i].h){
dp[i] = max(dp[i], dp[j]+1);
ans = max(ans,dp[i]);
}
}
}
return ans;
}
};