概述
题目描述:
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]).
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所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复