354. Russian Doll Envelopes 俄罗斯套娃信封问题

题目链接

tag:

  • Hard;
  • DP;

question:
  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)

Note: Rotation is not allowed.

Example:

Input: [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).

思路:
  本题给了我们一堆大小不一的信封,让我们像套俄罗斯娃娃那样把这些信封都给套起来,容易想到用 DP ,这是一种 brute force 的解法,首先要给所有的信封按从小到大排序,首先根据宽度从小到大排,如果宽度相同,那么高度小的再前面,这里用 STL 里面的 sort ,然后开始遍历,对于每一个信封,我们都遍历其前面所有的信封,如果当前信封的长和宽都比前面那个信封的大,那么我们更新dp数组,代码如下:

class Solution {
public:
    int maxEnvelopes(vector>& envelopes) {
        if (envelopes.empty() || envelopes[0].empty()) return 0;
        sort(envelopes.begin(), envelopes.end(), comparator);
        int res = 0, n = envelopes.size();
        vector dp(n, 1);
        for (int i=0; i envelopes[j][0] && envelopes[i][1] > envelopes[j][1])
                    dp[i] = max(dp[i], dp[j] + 1);
            }
            res = max(res, dp[i]);
        }
        return res;
    }
    
    static bool comparator(vector a, vector b) {
        if (a[0] == b[0])
            return a[1] < b[1];
        else
            return a[0] < b[0];
    }
};

你可能感兴趣的:(354. Russian Doll Envelopes 俄罗斯套娃信封问题)