题目链接:https://leetcode.com/problems/russian-doll-envelopes/
题目:
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]).
思路:
类似于最长增长子串,不同的在于判断增长的条件不同,以及需要先将数组排序。
c[i]表示从0到i个envelopes,最大可以包含的数目,用a数组记录到i的时候,最大包含数目的最大的envelopes的size。
状态转移方程:c[i]=max{c[j]+1} envelopes[i][0]>envelopes[j][0]&&envelopes[i][1]>envelopes[j][1]
0<=j<i
排序时间复杂度O(nlogn),dp时间复杂度O(n^2),dp的时候其实可以进一步用二分搜索优化成O(nlogn)的。不过因为下面的做法也能ac就懒得优化 了。= =
算法:
private void quickSort(int[][] array, int beg, int end) { if (beg >= end || array == null) return; int p = partition(array, beg, end); quickSort(array, beg, p - 1); quickSort(array, p + 1, end); } private int partition(int[][] array, int beg, int end) { int first = array[beg][0]; int i = beg, j = end; while (i < j) { while (array[i][0] <= first && i < end) { i++; } while (array[j][0] > first && j >= beg) { j--; } if (i < j) { int tmp[] = array[i]; array[i] = array[j]; array[j] = tmp; } } if (j != beg) { int tmp[] = array[j]; array[j] = array[beg]; array[beg] = tmp; } return j; } public int maxEnvelopes(int[][] envelopes) { if (envelopes.length == 0) { return 0; } int a[][] = new int[envelopes.length][2];// 到i最后一个套娃的大小 int c[] = new int[envelopes.length];// c[i]表示从0到i个envelopes,最大可以包含的数目 c[0] = 1; quickSort(envelopes, 0, envelopes.length - 1); a[0] = envelopes[0]; int max = 1; for (int i = 1; i < envelopes.length; i++) { int m = 1; boolean flag = true; for (int j = i - 1; j >= 0; j--) { if (envelopes[i][0] > a[j][0] && envelopes[i][1] > a[j][1]) { flag = false; if (m <= c[j] + 1) { m = c[j] + 1; a[i] = envelopes[i]; } } } if (flag) { a[i] = envelopes[i]; } c[i] = m; max = Math.max(max, m); } return max; }