• 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 }
  • 相关阅读:
    C#关于MSMQ通过HTTP远程发送专有队列消息的问题
    ASP.NET中进行消息处理(MSMQ) 三
    ASP.NET中进行消息处理(MSMQ) 二
    ASP.NET中进行消息处理(MSMQ) 一
    日志插件 log4net 的使用
    在64位windows下使用instsrv.exe和srvany.exe创建windows服务
    Windows下MemCache多端口安装配置
    把页面上DIV元素生成图片
    memcached协议
    没钱买珍珠首饰,能够画一个
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4893971.html
Copyright © 2020-2023  润新知