码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-06-29 06:39:24      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

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[n];
        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[n];
        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

 

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

标签:

原文地址:http://www.cnblogs.com/fu11211129/p/5625566.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!