• 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
  • 相关阅读:
    iOS项目中的网络请求和上下拉刷新封装
    iOS 自定义转场动画浅谈
    python中通过xlwt、xlrd和xlutils操作xls
    Python: PS 滤镜--水波特效
    Python: PS 滤镜--旋涡特效
    Python: PS 滤镜--USM 锐化
    Python: PS 滤镜--素描
    Python: PS 图像调整--饱和度调整
    Python: PS 图像特效 — 模糊玻璃
    Python: PS 滤镜--表面模糊
  • 原文地址:https://www.cnblogs.com/fu11211129/p/5625566.html
Copyright © 2020-2023  润新知