LeetCode OJ: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.

简单点讲,题目的意思就是,一连串数字,不能去相邻的值,那么怎么样才能取到其中的最大值。DP,表达式为:ret[i] = max(ret[i - 1], ret[i - 2] + nums[i]);

一开始想还有一种可能就是ret[i - 1]可能就是ret[i - 2],但是这里不影响,因为还是ret[i - 2] + num[i]较大,代码如下:

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

java版本的代码和上面一样,如下所示:

 1 public class Solution {
 2     public int rob(int[] nums) {
 3         int sz = nums.length;
 4         if(sz == 0) 
 5             return 0;
 6         if(sz == 1) 
 7             return nums[0];
 8         if(sz == 2) 
 9             return Math.max(nums[0], nums[1]);
10         int [] ret = new int [sz];
11         ret[0] = nums[0];
12         ret[1] = Math.max(nums[0], nums[1]);
13         for(int i = 2; i < sz; ++i){
14             ret[i] = Math.max(ret[i-2] + nums[i], ret[i-1]);
15         }
16         return ret[sz-1];
17     }
18 }

 

转载于:https://www.cnblogs.com/-wang-cheng/p/4893971.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值