LC.P354[俄罗斯套娃信封问题]

方法一:动态规划

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public int maxEnvelopes(int[][] envelopes) {
int n = envelopes.length;
if (n == 0) return 0;

Arrays.sort(envelopes, (a, b) -> {
if (a[0] != b[0]) return a[0] - b[0]; // 按宽度升序
else return b[1] - a[1]; // 按高度降序
});

int[] f = new int[n];
Arrays.fill(f, 1);
int ans = 1;
for (int i = 1; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (envelopes[j][1] < envelopes[i][1]) {
f[i] = Math.max(f[i], f[j] + 1);
}
}
ans = Math.max(ans, f[i]);
}
return ans;
}
}
  • 时间复杂度:$O(n^2)$
  • 空间复杂度:$O(n)$

方法二:二分查找+动态规划

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public int maxEnvelopes(int[][] envelopes) {
int n = envelopes.length;
if (n == 0) return 0;
Arrays.sort(envelopes, (a, b) -> {
if (a[0] != b[0]) return a[0] - b[0]; // 按宽度升序
else return b[1] - a[1]; // 按高度降序
});
List<Integer> list = new ArrayList<>();
list.add(envelopes[0][1]);
for (int i = 1; i < n; ++i) {
int h = envelopes[i][1];
if (h > list.get(list.size() - 1)) {
list.add(h);
} else {
int index = binarySearch(list, h);
list.set(index, h);
}
}
return list.size();
}

private int binarySearch(List<Integer> list, int target) {
int left = 0, right = list.size() - 1;
while (left < right) {
int mid = left + right >> 1;
if (list.get(mid) >= target) right = mid;
else left = mid + 1;
}
return left;
}
}
  • 时间复杂度:$O(nlogn)$
  • 空间复杂度:$O(n)$