我是靠谱客的博主 默默饼干,最近开发中收集的这篇文章主要介绍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]).

自己写了一个回溯的算法,先排序,然后计算从envelopes[0]为起点,能装入的最大包裹数,然后从envelopes[1]为起点,以此类推。遗憾的是超时了,代码如下:

public class Solution {
    public int maxEnvelopes(int[][] envelopes) {
        int n=envelopes.length;
        if(n==0)
        	return 0;
        Arrays.sort(envelopes, new Comparator<int[]>(){
            public int compare(int[] arr1, int[] arr2){
                if(arr1[0] == arr2[0])
                    return arr1[1] - arr2[1];
                else
                    return arr1[0] - arr2[0];
           } 
        });
		int max=0;
		boolean[] started=new boolean[envelopes.length];
		for(int i=0;i<n;i++){
			if(!started[i]){
				max=max>getMaxEnvelopes(envelopes, i, started)?max:getMaxEnvelopes(envelopes, i, started);
			}
		}
		return max;
    }
	
	public int getMaxEnvelopes(int[][] envelopes,int startIndex,boolean[] started){
		int max=1;
		int width=envelopes[startIndex][0];
		int height=envelopes[startIndex][1];
		for(int i=startIndex+1;i<envelopes.length;i++){
			if(envelopes[i][0]>width&&envelopes[i][1]>height){
				started[i]=true;
				int num=getMaxEnvelopes(envelopes, i , started)+1;
				max=max>num?max:num;
			}
		}
		return max;
	}
}
大神的解法,width升序,height降序!:

public class Solution {
    public int maxEnvelopes(int[][] envelopes) {
	    if(envelopes == null || envelopes.length == 0 
	       || envelopes[0] == null || envelopes[0].length != 2)
	        return 0;
	    Arrays.sort(envelopes, new Comparator<int[]>(){
	        public int compare(int[] arr1, int[] arr2){
	            if(arr1[0] == arr2[0])
	                return arr2[1] - arr1[1];
	            else
	                return arr1[0] - arr2[0];
	       } 
	    });
	    int dp[] = new int[envelopes.length];
	    int len = 0;
	    for(int[] envelope : envelopes){
	        int index = Arrays.binarySearch(dp, 0, len, envelope[1]);
	        if(index < 0)
	            index = -(index + 1);
	        dp[index] = envelope[1];
	        if(index == len)
	            len++;
	    }
	    return len;
	}
}


最后

以上就是默默饼干为你收集整理的Russian Doll Envelopes的全部内容,希望文章能够帮你解决Russian Doll Envelopes所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(39)

评论列表共有 0 条评论

立即
投稿
返回
顶部