zoukankan      html  css  js  c++  java
  • leetcode------House Robber

    标题: House Robber
    通过率: 27.5%
    难度: 简单

    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.

    动态规划:一个数组取数字,不能取相邻的数字,然后求能取出数字的最大和,用一个用一个长度问len+1的数组res去维护,位置是1的放num[0]

    然后res[i]表示,到第i个房子时拿到的最大和是多少,

    res[i]=max(res[i-1],res[i-2]+num[i-1])

    表示到i时,如果取i说明i-1是不取的,那么就要把i-2位置的数加上num【i-1】数,如果不取i的数,就是说明取了i-1的数,那么到位置i时最大值等于i-1位置的最大值

    直接看代码:

     1 public class Solution {
     2     public int rob(int[] num) {
     3         int len=num.length;
     4         if(len==0)return 0;
     5         if(len==1)return num[0];
     6         int [] res=new int[len+1];
     7         res[0]=0;
     8         res[1]=num[0];
     9         for(int i=2;i<len+1;i++){
    10             res[i]=Math.max(res[i-1],res[i-2]+num[i-1]);
    11         }
    12         return res[len];
    13         
    14     }
    15 }
  • 相关阅读:
    bzoj3688 折线统计
    bzoj3678 wangxz与OJ
    「6月雅礼集训 2017 Day8」route
    「6月雅礼集训 2017 Day8」gcd
    [ SHELL编程 ] 编程常用的ORACLE相关命令
    Oracle数据库备份/导入工具
    Oracle数据文件迁移到裸设备
    Oracle数据文件转移操作
    Oracle重建表空间操作实例
    Linux性能测试分析命令_sar
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4391020.html
Copyright © 2011-2022 走看看