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 }
  • 相关阅读:
    学生分数排序
    union 的一个简单例子,搜狗笔试题
    枚举的初始化赋值
    unsigned 赋值负数输出情况 & printf输出格式
    sizeof中的表达式不执行
    三级指针:百度试题
    生成器案例,#采集日志
    简述装饰器
    装饰器(转载)
    python写监控并发警报邮件
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4893971.html
Copyright © 2011-2022 走看看