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 }
  • 相关阅读:
    PHP7函数大全(4553个函数)
    Mysql 查看连接数,状态 最大并发数
    linux安装git
    PHP new StdClass() 创建空对象
    PHP 如何向关联数组指定的 Key 之前插入元素
    php 常用 小知识点
    PHP激活用户注册验证邮箱
    php rsa 加密、解密、签名、验签
    PHP支付接口RSA验证
    [2018-12-07]用ABP入门DDD
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4391020.html
Copyright © 2011-2022 走看看