動態規劃 hard LeetCode 354. Russian Doll Envelopes

這周依舊是動態規劃,老師說動態規劃的內容很多,有很多變種,所以講了很久,前幾天看到一篇文章說動態規劃不是一種算法而是一種思想,覺得挺有道理的,畢竟它不像其他算法那樣有一個固定的方法,但是某種程度上來說也是有的,嗯,進入正題吧,不糾結這個問題了。下面看一看這周的題吧,難度爲hard,題目如下:

--------------------------題目-----------------------------

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

--------------------------題解------------------------------

題目很好理解,用俄羅斯套娃來理解,當一個信封的長寬都大於另一個信封時,另一個信封就可以裝進這一個信封中,很符合生活常識吧,需要嚴格的大於。我想這裏應該是忽略厚度吧,要不然最外面的信封會被撐爆的吧。動態規劃的思想就是我只需要知道上一個狀態的結果就行了,不需要知道上一個狀態具體是什麼狀態,放到這道題的話就是我只需要知道那個長寬都小於我手上這個信封的信封裝了多少個信封而不需要知道具體都有那些信封,具體看代碼的註釋吧。

#include <iostream>
#include <vector>
#include <algorithm>
#include <memory.h>
using namespace std;

class Solution {
public:
	static bool cmp1(pair<int,int> a,pair<int,int> b)
	{
		return a.first<b.first;
	}
	static bool cmp2(pair<int,int> a,pair<int,int> b)
	{
		return a.second<b.second;
	}
    int maxEnvelopes(vector<pair<int, int> >& envelopes) {
        sort(envelopes.begin(),envelopes.end(),cmp1);
        sort(envelopes.begin(),envelopes.end(),cmp2);//桶排序
        int en[10000];//不能像傳統那樣用長寬作爲兩個維度,感覺會爆內存,題目也沒給數據範圍
        memset(en,0,sizeof(en));
        int l=envelopes.size();
        int ans=0;
        for(int i=0;i<l;i++)
        {
        	int w=envelopes[i].first;
        	int h=envelopes[i].second;
        	en[i]=1;
        	for(int j=0;j<i;j++)
        	{
        		int nw=envelopes[j].first;
        		int nh=envelopes[j].second;
        		if(w>nw&&h>nh)
        		en[i]=max(en[i],en[j]+1);//狀態轉移方程,只有可能裝下當前信封前面的信封,所以遍歷一下前面的這些信封,找到使當前狀態最大的結果
			}
			ans=max(ans,en[i]);
		}
    	return ans;
	}
    
};
題還是比較簡單的,之前按照兩個維度寫過不了,後來觀察了一下發現兩個維度的話前後狀態與這兩個維度並沒有什麼聯繫,所以就沒必要用兩個維度了,就用向量下標就好了。
---------------------分割線----------------------
see you next illusion


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章