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 andit 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 tonightwithout alerting the police.
解题思路:
房间一共有N个,先判断到目前为止,前i个房间能获得最多的金钱。
典型的动态规划。
其中转移方程如下:
maxV[i] = max( maxV[i - 2] + a[i],maxV[i-1]);
其中数组a[i]为第i个房间隐藏的金钱。maxV[i]表示前i个房间能获得的最多的钱。
代码如下:
classSolution{public:introb(vector<int>&nums){//处理特殊情况if(nums.empty())return0;if(nums.size()==1)returnnums[0];if(nums.size()==2)returnnums[0]>nums[1]?nums[0]:nums[1];//处理正常情况int*maxV=newint[nums.size()];maxV[0]=nums[0];maxV[1]=nums[0]>nums[1]?nums[0]:nums[1];for(inti=2;i<nums.size();++i){maxV[i]=max(maxV[i-2]+nums[i],maxV[i-1]);}intresult=maxV[nums.size()-1];deletemaxV;maxV=NULL;returnresult;}};
2016-08-31 21:49:51
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。