国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

Leetcode 198. House Robber

2019-11-10 19:34:15
字體:
供稿:網(wǎng)友

You are a PRofessional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

s思路: 1. 用dp.從“不能搶相鄰兩家的錢”這個條件入手,例如:

num 5 7 10 2 9 13
cur 5 7 15 15 24 28
pre 0 5 7 15 15 24

如上圖,cur表示當(dāng)前位置時搶或不搶的最大值,pre表示前一個位置搶或不搶中最大。那么第二天當(dāng)前位置有7,這就要比較了:如果搶,則總共就是7+上一個位置的pre,即:7+0=7;不搶,則就是上一個位置的cur=5,max(7,5)=7,遞推關(guān)系:pre=cur, cur=max(cur,pre+nums[i])。 2. 為什么這類題可以用dp?首先,求最值問題,很多都可以考慮用dp,這個還不關(guān)鍵。最關(guān)鍵的是,搶到最多錢是個過程,且在過程中要一直保存搶到做多,就應(yīng)為這個,我們可以把全程搶最多分割成n個小任務(wù)。又根據(jù)條件“不能搶相鄰兩家的錢”,這些任務(wù)之間還有聯(lián)系,根據(jù)這個關(guān)系來得到遞推關(guān)系即可! 3. “不能搶相鄰兩家的錢”,根據(jù)這個條件,說明只需要維護(hù)兩個狀態(tài),當(dāng)前位置和前一個位置的最大,然后不斷更新當(dāng)前和前一個位置。

//方法1:dpclass Solution {public: int rob(vector<int>& nums) { // if(nums.empty()) return 0; int pre=0,cur=nums[0]; for(int i=1;i<nums.size();i++){ int tmp=max(cur,pre+nums[i]); pre=cur; cur=tmp; } return cur; }};
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 观塘区| 嘉黎县| 建始县| 敦煌市| 呼伦贝尔市| 寿光市| 栖霞市| 二连浩特市| 察隅县| 吕梁市| 健康| 白城市| 上林县| 会泽县| 台东市| 韶关市| 福贡县| 翼城县| 龙川县| 铁力市| 巴马| 融水| 鄄城县| 阳城县| 壤塘县| 扎赉特旗| 西乌| 崇仁县| 武城县| 什邡市| 宁波市| 资溪县| 深州市| 建平县| 乌拉特前旗| 澳门| 冷水江市| 建水县| 大关县| 福清市| 马尔康县|