zoukankan      html  css  js  c++  java
  • 198. 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.

    题目的大致意思是,给定一个数组,求出数组中不相邻元素的最大值。这是一道动态规划题目,参考这里,假定数组为nums={5,3,14,20},存放当前最大值的数组dp,

    当i=0,当前最大值 dp[0] = 5

    当i=1,当前最大值dp[1] = max(num[0],num[1])

    当i=2,当前最大的值dp[2] = max(nums[i] + dp[i-2],dp[i - 1]) #当前的最大值=max(前一个(上一个的上一个)最大值+当前的值,上一个最大值)

    ....

    当i=n(n>=2),当前最大的值dp[n] = max(nums[i] + dp[i-2],dp[i - 1])

    
    public int rob(int[] nums) {
    
            if(nums.length == 0) 
                return 0;
            if(nums.length == 1)
                return nums[0];
            int dp[] = new int[nums.length];
            dp[0] = nums[0];
            dp[1] = Math.max(dp[0],nums[1]);
            for(int i = 2 ;i < nums.length; i++)
            {
                dp[i] = Math.max(nums[i]+dp[i - 2],dp[i - 1]);
            }
            return dp[nums.length - 1];
        }
    
    

    上面使用的是动态规划方法,主要维护的是当前位置的前一个和上一个值,即不邻近与邻近的值,那么我们可以使用两个变量来存储着两个位置的值,思想也类似DP。下面是代码

    
    public int rob(int[] nums) {
        int a=0,int b = 0;
        for(int i = 0; i < nums.length; i++){
            if(i % 2 == 0)
               a = Math.max(a + nums[i],b);
           else
               b = Math.max(a,b+num[i]);
        }
    }
    
    
  • 相关阅读:
    database使用
    画图工具
    宝塔面板权限不足问题解决
    nginx查看并发数量
    台式机未插入扬声器或者耳机
    键盘出现乱码解决
    lnmp宝塔面板问题
    nginx+mysql双主搭建
    zabbix客户端安装
    java生产条形码
  • 原文地址:https://www.cnblogs.com/wxshi/p/7802398.html
Copyright © 2011-2022 走看看