Leetcode 198. House Robber

198. House Robber

  • Total Accepted: 80861
  • Total Submissions: 227576
  • Difficulty: Easy

 

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.

 

思路:假设dp[i]表示的nums[0],nums[1]...nums[i]之间形成的最大可得到的money。显然分盗窃第i间和不盗窃第i间2种情况,所以dp[i]=max(dp[i-2]+nums[i],dp[i-1])

 

代码:

 1 class Solution {
 2 public:
 3     int rob(vector<int>& nums) {
 4         int n=nums.size(),i;
 5         //int *dp=new int[2];
 6         int dp[2]={0};
 7         for(i=0;i<n;i++){
 8             dp[i%2]=max(dp[i%2]+nums[i],dp[(i+1)%2]);
 9         }
10         return max(dp[0],dp[1]);
11     }
12 };

 

 

posted @ 2016-07-26 18:05  Deribs4  阅读(104)  评论(0编辑  收藏  举报