leetCode 198. House Robber | 動態規劃

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.ide

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.spa

解題思路:orm

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

典型的動態規劃。io

其中轉移方程以下:class

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

其中數組a[i]爲第i個房間隱藏的金錢。maxV[i]表示前i個房間能得到的最多的錢。call


代碼以下:margin

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

相關文章
相關標籤/搜索