您的位置:首页 > 运维架构

leetcode@ [354] Russian Doll Envelopes (Dynamic Programming)

2016-06-29 05:45 609 查看
https://leetcode.com/problems/russian-doll-envelopes/

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]).

class pair {
public int width;
public int height;

public pair(int w, int h) {
super();
this.width = w;
this.height = h;
}
}

class pairComparator implements Comparator {
public int compare(Object o1, Object o2) {
pair p1 = (pair) o1;
pair p2 = (pair) o2;

if(p1.width < p2.width) {

return -1;

} else if(p1.width == p2.width) {

if(p1.height == p2.height) {
return 0;
} else if(p1.height < p2.height) {
return -1;
} else {
return 1;
}

} else {

return 1;
}
}
}

public class Solution {
public int maxEnvelopes(int[][] envelopes) {

int n = envelopes.length;
if(n == 0) {
return 0;
}

pair pr[] = new pair
;
for(int i=0; i<n; ++i) {
pair p = new pair(envelopes[i][0], envelopes[i][1]);
pr[i] = p;
}

Arrays.sort(pr, new pairComparator());

int[] dp = new int
;
int rs = -1;
for(int i=0; i<n; ++i) {
int mmax = 0;
for(int pre=0; pre<i; ++pre) {
if(pr[pre].width < pr[i].width && pr[pre].height < pr[i].height) {
mmax = Math.max(mmax, dp[pre]);
}
}
dp[i] = mmax + 1;
rs = Math.max(rs, dp[i]);
}

return rs;
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: