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

Posted 流白

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode@ [354] Russian Doll Envelopes (Dynamic Programming)相关的知识,希望对你有一定的参考价值。

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)的主要内容,如果未能解决你的问题,请参考以下文章

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

[动态规划] leetcode 354 Russian Doll Envelopes

LeetCode 354. Russian Doll Envelopes

leetcode354. Russian Doll Envelopes

第十二周 Leetcode 354. Russian Doll Envelopes(HARD) LIS问题

354. Russian Doll Envelopes