题意:给定一个二位数组,数组中记录一组信封的长宽,现在按照小信封外套大信封的方法,求最多能套几层
思路:把二位数组转化为list,然后按照宽排序,之后用动态规划,dp[i]记录第i个信封能存的最大的信封数,其中dp[i]=dp[j]+1其中dp[j]是在从比dp[i]的宽度小的dp中找到的最大值
class Nodes {
int w;
int h;
public Nodes(int i, int j) {
w = i;
h = j;
}
}
class NodesComparator implements Comparator<Nodes> {
public int compare(Nodes n1, Nodes n2) {
return n1.w - n2.w;
}
}
public class Solution {
public int maxEnvelopes(int[][] envelopes) {
int w = envelopes.length;
if(w == 0)
return 0;
List<Nodes> list = new ArrayList<Nodes> ();
for(int i=0;i<w;i++) {
list.add(new Nodes(envelopes[i][0], envelopes[i][1]));
}
Collections.sort(list, new NodesComparator());
int[] dp = new int[w];
dp[0] = 1;
int pres = 0;
int pree = 0;
int curs = 0;
for(int i=1;i<w;i++) {
if(list.get(i).w == list.get(pree).w) {
} else {
pres = curs;
pree = i;
curs = i;
}
for(int j=0;j<pree;j++) {
if(list.get(i).h>list.get(j).h && dp[j]+1>dp[i])
dp[i] = dp[j]+1;
}
if(dp[i] == 0)
dp[i] = 1;
}
int res = 0;
for(int i=0;i<w;i++)
{
if(res<dp[i])
res = dp[i];
}
return res;
}
}