/** * 给出一些信封,每个信封用宽度和高度的整数对形式(w,h)表示,当一个信封的宽度和高度都比另外一个信封大的时候,那么就可以放进去, * 请计算最多能套几层? * 二维最长递增子序列问题 */
public class Solution5 {
public static void main(String[] args) {
int[][] nums = new int[][]{ { 1,8},{ 2,3},{ 5,4},{ 5,2},{ 6,7},{ 6,4}};
System.out.println(maxNum(nums));
}
static int maxNum(int[][] nums) {
Arrays.sort(nums, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[0] == o2[0] ? o2[1] - o1[1] : o1[0] - o2[0];
}
});
int[] height = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
height[i] = nums[i][1];
}
return LIS(height);
}
/** dp[i]表示以height[i]结尾的最长递增子序列的长度*/
static int LIS(int[] height) {
int[] dp = new int[height.length];
// base case
Arrays.fill(dp, 1);
for (int i = 0; i < height.length; i++) {
for (int j = 0; j < i; j++) {
if (height[i] > height[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
}
int res = Integer.MIN_VALUE;
for (int i = 0; i < dp.length; i++) {
res = Math.max(res, dp[i]);
}
return res;
}
}
还没有评论,来说两句吧...