LeetCode 354. 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]).

该题目属于接龙型的DP,接龙型的DP的一个巨大的特点就是按照一定的顺序排序后,后面的的可以在前面的数据的+1的基础之上完成

java

class Solution {
    public int maxEnvelopes(int[][] envelopes) {
        if (envelopes == null || envelopes.length == 0 || envelopes[0] == null || envelopes[0].length == 0) {
            return 0;
        }
        Comparator cmp = new Comparator() {
            public int compare(int[] arr1, int[] arr2) {
                if (arr1[0] == arr2[0]) {
                    return arr1[1] - arr2[1];
                } else {
                    return arr1[0] - arr2[0];
                }
            }
        };
        Arrays.sort(envelopes, cmp);
        // state
        int[] f = new int[envelopes.length];
        // initialize
        Arrays.fill(f, 1);
        int max = 1;
        // function
        for (int i = 1; i < envelopes.length; i++) {
            for (int j = 0; j < i; j++) {
                if (envelopes[j][0] < envelopes[i][0] && envelopes[j][1] < envelopes[i][1]) {
                    f[i] = Math.max(f[j] + 1, f[i]);
                }
            }
            max = Math.max(f[i], max);
        }
        // answer
        return max;
    }
}


你可能感兴趣的:(leetcode)