【动归】A021_俄罗斯套娃信封问题(dp | 二分(待办))

一、题目描述

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)

Note:Rotation is not allowed.

Input: [[5,4],[6,4],[6,7],[2,3]]
Output: 3 
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).

二、题解

方法一:dp

其实这是一个最长上升子序列的变形问题,想一下如果信封的某一个属性是升序的,对另一个属性进行的大小进行判别就可以把问题转换为一维的 dp 了。

public int maxEnvelopes(int[][] enves) {
  int N = enves.length;
  if (N == 0) return 0;
  Arrays.sort(enves, new Comparator<int[]>() {
      public int compare(int[] a, int[] b) {
          if (a[0] == b[0]) {
              return b[1] - a[1];
          }
          return a[0] - b[0];
      }
  });

  int[] dp = new int[N];
  Arrays.fill(dp, 1);
  int max = 1;

  for (int i = 1; i < N; i++) {
  for (int j = 0; j < i; j++)
  if ( enves[j][1] < enves[i][1])
    dp[i] = Math.max(dp[i], dp[j] + 1);
      if (dp[i] > max)
          max = dp[i];
  }
  return max;
}

复杂度分析

  • 时间复杂度: O ( n 2 ) O(n^2)
  • 空间复杂度: O ( n ) O(n)

方法二:二分(待做)


复杂度分析

  • 时间复杂度: O ( ) O()
  • 空间复杂度: O ( ) O()
发布了495 篇原创文章 · 获赞 105 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/104856133