zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    MultipartFile 多文件上传的应用
    启动关闭zookeeper集群的脚本
    分布式锁
    NFS部署教程
    Docker安装(Debian8)-构建简单的SpringBoot应用
    Nginx实战-后端应用健康检查
    分布式文件系统FastDFS安装教程
    Redis缓存使用技巧
    WebSocket原理与实践
    HashMap中ConcurrentModificationException异常解读
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4893971.html
Copyright © 2011-2022 走看看