LeetCode No.354 Russian Doll Envelopes

来源:互联网 发布:网络遥控器怎么用法 编辑:程序博客网 时间:2024/06/05 05:28

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

===================================================================

题目链接:https://leetcode.com/problems/russian-doll-envelopes/

题目大意:给定一个表示套娃宽和高的序列,只有当一个套娃的宽和高都比原来的套娃的宽和高大的时候才能套进去,求最多能套几个套娃。

思路:这个跟求最长上升子序列的题目类似,先对套娃进行排序,排序方式如下:

1、宽相同则按高度升序排序。

2、否则按宽度升序排序。

static bool cmp ( const pair <int, int>& a , const pair <int, int>& b ){    if ( a.first == b.first )        return a.second < b.second ;    return a.first < b.first ;}


然后使用动态规划

1、初始化所有dp[i] = 1 

2、dp[i]表示能套入i 时最多能套多少个套娃

参考代码:

class Solution {public:    int maxEnvelopes(vector<pair<int, int>>& envelopes) {        int n = envelopes.size() ;        sort ( envelopes.begin() , envelopes.end() , cmp ) ;        vector <int> dp ( n + 1 , 1 ) ;        for ( int i = 0 ; i < n - 1 ; i ++ )        {            for ( int j = i + 1 ; j < n ; j ++ )            {                if ( envelopes[j].first > envelopes[i].first && envelopes[j].second > envelopes[i].second )                    dp[j] = max ( dp[j] , dp[i] + 1 ) ;            }        }        int ans = 0 ;        for ( int i = 0 ; i < n ; i ++ )            ans = max ( ans , dp[i] ) ;        return ans ;    }private :    static bool cmp ( const pair <int, int>& a , const pair <int, int>& b )    {        if ( a.first == b.first )            return a.second < b.second ;        return a.first < b.first ;    }};


0 0
原创粉丝点击