leetcode House Robber II

小鱼儿 2022-08-01 11:08 190阅读 0赞

题目

Note: This is an extension of House Robber.

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

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.

题目来源:https://leetcode.com/problems/house-robber-ii/

分析

上一个题house robber的解析见:http://blog.csdn.net/u010902721/article/details/46583815

这个题在上一道题的基础上加了一个限制条件,也就是首和尾也是相邻的。那就拆开做,分别去掉第一个元素和最后一个元素后再用第一道题的方案去求解。最大值就是本题的答案。

代码

  1. class Solution {
  2. public:
  3. int rob1(vector<int>& nums, int begin, int end) {
  4. int size = end - begin + 1;
  5. if(size == 1)
  6. return nums[begin];
  7. vector<int> dp(size + 1, 0);
  8. dp[size-1] = nums[end];
  9. int ans = dp[size - 1];
  10. int max_next = 0;
  11. for(int i = end - 1; i >= begin; i--){
  12. dp[i - begin] = nums[i] + max_next;
  13. ans = max(ans, dp[i - begin]);
  14. max_next = max(dp[i - begin +1], max_next);
  15. }
  16. return ans;
  17. }
  18. int rob(vector<int>& nums) {
  19. int len = nums.size();
  20. if(len == 0)
  21. return 0;
  22. if(len == 1)
  23. return nums[0];
  24. return max(rob1(nums, 0, len - 2), rob1(nums, 1, len - 1));
  25. }
  26. };

发表评论

表情:
评论列表 (有 0 条评论,190人围观)

还没有评论,来说两句吧...

相关阅读