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]).
先通过w按照升序排序,在按照h的升序排序(当w相同时,h降序),再结合LIS求解,程序如下所示:
class Solution {
class Node {
int weight;
int height;
Node(int w, int h){
weight = w;
height = h;
}
}
List<Node> list = new ArrayList<>();
public int maxEnvelopes(int[][] envelopes) {
if (envelopes.length == 0){
return 0;
}
for (int i = 0; i < envelopes.length; ++ i){
list.add(new Node(envelopes[i][0], envelopes[i][1]));
}
Collections.sort(list, new Comparator<Node>(){
@Override
public int compare(Node m, Node n){
if (m.weight != n.weight){
return m.weight - n.weight;
}
return n.height - m.height;
}
});
int len = list.size();
int[] heightArr = new int[len];
for (int i = 0; i < len; ++ i){
heightArr[i] = list.get(i).height;
}
return LIS(heightArr);
}
public int LIS(int[] height){
int len = height.length;
if (len <= 1){
return len;
}
int[] array = new int[len];
int maxVal = 0;
for (int i = 1; i < len; ++ i){
for (int j = 0; j < i; ++ j){
if (height[i] > height[j]){
array[i] = Math.max(array[i], array[j] + 1);
}
}
maxVal = Math.max(maxVal, array[i]);
}
return maxVal + 1;
}
}