leetcode 198

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.

求出一个数列中不相邻的的组合的各个数相加的的最大值。

采用动态规划的思想。

对于第i个房间我们的选择是偷和不偷, 

如果决定是偷 则第i-1个房间必须不偷 那么 这一步的就是 re[i] = nums(i-1) + re[i-2] , 

假设re[i]表示打劫到第i间房屋时累计取得的金钱最大值.

如果是不偷, 那么上一步就无所谓是不是已经偷过, re[i] = re[i -1 ], 因此 re[i] =max(re[i-2] + nums(i-1), re[i-1] );  

利用动态规划,状态转移方程:re[i] = max(re[i - 1], re[i - 2] + nums[i - 1]).

代码如下:

 

 1 class Solution {
 2 public:
 3     int rob(vector<int>& nums) {
 4         int n = nums.size();
 5         if(n == 0)
 6         {
 7             return 0;
 8         }
 9         int * re = new int[n+1];
10         re[0] = 0;
11         re[1] = nums[0];
12         for(int i = 2; i < n+1; i++)
13         {
14             re[i] = max(re[i-1], re[i-2] + nums[i-1]);
15         }
16         return re[n];
17     }
18 };

 

posted @ 2016-11-09 11:05  花椰菜菜菜菜  阅读(260)  评论(0编辑  收藏  举报