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 is3([2,3] => [5,4] => [6,7]).

这道题看起来很复杂的样子,实际上想想,其实就是二维的LIS,所需要做的就是在按长度或者宽度来排序即可,然后在找当前最优解的过程中加入一个判断长度包含和宽度包含的逻辑判断即可,另外这道题如果用朴素的LIS方法做时间复杂度为O(n^2),这种情况下Python是过不了LeetCode的,Java则是勉强AC,lintcode就不要想了,然后这道题还有O(nlgn)的二分法解法,等DP课讲到的时候再实现,下面是状态方程和O(n^2)的代码

for every j < i
    dp[i] = max(dp[i], dp[j] + 1) if envelopes[i][0] > envelopes[j][0] and envelopes[i][1] > envelopes[j][1]

这里dp[i]的初始值为1
public class Solution {
    public int maxEnvelopes(int[][] envelopes) {
        int n = envelopes.length;
        if (n == 0 || envelopes == null 
            || envelopes[0].length == 0
            || envelopes[0] == null) {
                return 0;
            }

        int[] dp = new int[n];
        int result = 1;

        // 下面是java比较器的写法

        Arrays.sort(envelopes, new Comparator<int[]>() {
            public int compare(int[] a, int[] b) {
                if (a[0] != b[0]) {
                    return a[0] - b[0];
                } else {
                    return a[1] - b[1];
                }
            }
        });

        for (int i = 0; i < n; i++) {
            dp[i] = 1;
            for (int j = 0; j < i; j++) {
                if (envelopes[i][0] > envelopes[j][0]) {
                    if (envelopes[i][1] > envelopes[j][1]) {
                        dp[i] = Math.max(dp[i], dp[j] + 1);
                    }
                }
            }
            result = Math.max(dp[i], result);
        }

        return result;
    }
}

results matching ""

    No results matching ""