Leetcode-354. Russian Doll Envelopes

本文探讨了一个经典的信封套叠问题,通过动态规划的方法找到能够互相套叠的最大数量的信封组合。给出了一段C++实现代码,并通过示例说明了如何计算不同尺寸信封之间的套叠关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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

Subscribe to see which companies asked this question

Hide Tags Binary Search Dynamic Programming
Hide Similar Problems (M) Longest Increasing Subsequence

源码:

class Solution {
public:
	int maxEnvelopes(vector<pair<int, int>>& envelopes) {
		int size = envelopes.size();
		if (size == 0)return 0;
		if (size == 1)return 1;
		multimap<int, pair<int, int>>info;
		int sum = 0;
		for (int i = 0; i < size; i++){
			sum = envelopes[i].first + envelopes[i].second;
			info.insert(make_pair(sum, envelopes[i]));//按和进行排序
		}
		vector<int>re(info.size(), 0);
		vector<pair<int, int>>da;
		for (map<int, pair<int, int>>::iterator i = info.begin(); i != info.end(); i++)da.push_back((*i).second);
		re[0] = 1;
		size = da.size();
		int total_max = 1;
		for (int i = 1; i < size; i++){//寻找每一个位置
			int tmp_value = 0;
			int max = 0;
			for (int j = i - 1; j >= 0; j--){
				if (i<size&&j>=0&&da[i].first>da[j].first&&da[i].second>da[j].second){
					tmp_value = re[j] + 1;
					if (tmp_value > max)max = tmp_value;
				}
			}
			if (max == 0)re[i] = 1;
			else re[i] = max;
			if (re[i] >= total_max)total_max = re[i];
		}
		return total_max;
	}
};

Submission Result: Accepted  More Details 
Share your acceptance!

分析:这道的思路与leetcode-368Largest Divisible Subset的思路完全一样,详情请参照博客:http://blog.youkuaiyun.com/caoyan_12727/article/details/52904132

如果一个信封i要能装进另一个信封j,那么i的长要大于j的长且i的宽要大于j的宽,则我们可以先对每个信封的长和宽进行升序排序,然后记录每个信封当前可以装下的最大信封

数!!!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值