码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] House Robber II

时间:2015-06-03 00:42:11      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:

This problem is a little tricky at first glance. However, if you have finished the "House Robber" problem, this problem can simply be decomposed into two "House Robber" problems. Suppose there are n houses, since house 0 and n - 1 are now neighboring to each other, the solution is now the maximum of:

  1. rob houses 0 t0 n - 2;
  2. rob houses 1 to n - 1.
 1     int robHelper(vector<int>& nums, int left, int right){
 2         if (left == right) return nums[left];
 3         vector<int> money(right - left + 1, 0);
 4         money[0] = nums[left];
 5         money[1] = max(nums[left], nums[left + 1]);
 6         for (int i = 2; i <= right - left; i++)
 7             money[i] = max(money[i - 1], money[i - 2] + nums[left + i]);
 8         return money[money.size() - 1];
 9     }
10     int rob(vector<int>& nums) {
11         if (nums.empty()) return 0;
12         int n = nums.size();
13         if (n == 1) return nums[0];
14         return max(robHelper(nums, 0, n - 2), robHelper(nums, 1, n - 1));
15     }  

 

[LeetCode] House Robber II

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4548002.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!