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