溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

leetCode 198. House Robber | 動態(tài)規(guī)劃

發(fā)布時間:2020-07-25 09:38:03 來源:網(wǎng)絡(luò) 閱讀:1580 作者:313119992 欄目:開發(fā)技術(shù)

198. House Robber

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.

解題思路:

房間一共有N個,先判斷到目前為止,前i個房間能獲得最多的金錢。

典型的動態(tài)規(guī)劃。

其中轉(zhuǎn)移方程如下:

maxV[i] = max( maxV[i - 2] + a[i],maxV[i-1]);

其中數(shù)組a[i]為第i個房間隱藏的金錢。maxV[i]表示前i個房間能獲得的最多的錢。


代碼如下:

class Solution {
public:
    int rob(vector<int>& nums) 
    {
        //處理特殊情況
    	if (nums.empty())
    		return 0;
    	if (nums.size() == 1)
    		return nums[0];
    	if (nums.size() == 2)
    		return nums[0] > nums[1] ? nums[0] : nums[1];
    	//處理正常情況	
    	int * maxV = new int[nums.size()];
    
    	maxV[0] = nums[0];
    	maxV[1] = nums[0] > nums[1] ? nums[0] : nums[1];
    
    	for (int i = 2 ; i < nums.size() ; ++i)
    	{
    		maxV[i] = max(maxV[i - 2] + nums[i], maxV[i - 1]);
    	}
    
    	int result = maxV[nums.size() - 1];
    	delete maxV;
    	maxV = NULL;
    	return result;
    }
};


2016-08-31 21:49:51


向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI