信封的宽高为envelope的二维数组
宽为升序,宽相等时,高为降序
envelopes[j][1] < envelopes[i][1] 为啥高维度比较的是1,不是0呢,,数学没学好啊。二维数组 n行2列
// envelopes = [[w, h], [w, h]...]
f[i]表示以 envelopes[i][1] 这个数结尾的最长递增子序列的长度
class Solution {
public int maxEnvelopes(int[][] envelopes) {
if (envelopes.length == 0) {
return 0;
}
int n = envelopes.length;
Arrays.sort(envelopes, new Comparator<int[]>() {
public int compare(int[] e1, int[] e2) {
if (e1[0] != e2[0]) {
return e1[0] - e2[0];
} else {
return e2[1] - e1[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;
}
}
基于二分查找的动态规划
class Solution {
public int maxEnvelopes(int[][] envelopes) {
if (envelopes.length == 0) {
return 0;
}
int n = envelopes.length;
Arrays.sort(envelopes, new Comparator<int[]>() {
public int compare(int[] e1, int[] e2) {
if (e1[0] != e2[0]) {
return e1[0] - e2[0];
} else {
return e2[1] - e1[1];
}
}
});
List<Integer> f = new ArrayList<Integer>();
f.add(envelopes[0][1]);
for (int i = 1; i < n; ++i) {
int num = envelopes[i][1];
if (num > f.get(f.size() - 1)) {
f.add(num);
} else {
int index = binarySearch(f, num);
f.set(index, num);
}
}
return f.size();
}
public int binarySearch(List<Integer> f, int target) {
int low = 0, high = f.size() - 1;
while (low < high) {
int mid = (high - low) / 2 + low;
if (f.get(mid) < target) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
}