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<vector<int>>& envelopes) {
        if (envelopes.empty() || envelopes[0].empty()) return 0;
        sort(envelopes.begin(), envelopes.end(), comparator);
        int res = 0, n = envelopes.size();
        vector<int> dp(n, 1);
        for (int i=0; i<n; ++i) {
            for (int j=0; j<i; ++j) {
                if (envelopes[i][0] > 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<int> a, vector<int> b) {
        if (a[0] == b[0])
            return a[1] < b[1];
        else
            return a[0] < b[0];
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,458评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,980评论 0 23
  • vector迭代器可以加减整数next:下一个迭代器prev:前一个迭代器INT_MAX = 2^31-1,INT...
    DaiMorph阅读 191评论 0 0
  • 将美好埋在昨天。蔷薇依旧鲜艳,不知疲倦。 翻阅简书文海,讥笑于自己的混迹,感伤混杂着谦逊,蹑手蹑脚走过一座座山丘,...
    ISD丨墨白阅读 347评论 0 3
  • 520亲子成长迹|05 这一周柳小宝开始愿意开始念绘本给妈妈听,愿意尝试画一些小作品,愿意自己用点读笔听鹅妈妈,愿...
    请叫我王青羽阅读 293评论 0 2