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.

    此题为动态规划,最优子结构性质,即整体的最优解依赖于局部的最优解,但不一定是相邻前一个的局部最优解,也就把贪心选择排除出去了。接下来就是重叠子问题,通过存储进dp数组来保存到第i个房子的最优解。代码如下:

    public class Solution {

        public int rob(int[] nums) {

            int[] dp = new int[nums.length];

            if(nums.length==0) return 0;

            if(nums.length==1) return nums[0];

            dp[0] = nums[0];

            dp[1] = Math.max(nums[0],nums[1]);

            for(int i=2;i<nums.length;i++){

                dp[i]= Math.max(dp[i-2]+nums[i],dp[i-1]);

            }

            return dp[nums.length-1];

        }

    }

  • 相关阅读:
    弹出层layer的使用
    SQL Server SQL分页查询
    C#过滤html标签
    SQLServer ForXmlPath应用
    js调用soapWebService服务
    MediaWiki使用指南
    阿里云金融云服务器配置
    VS无法启动 IISExpress web 服务器
    mysql服务突然丢失解决方案
    [k8s]通过openssl生成证书
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6357448.html
Copyright © 2011-2022 走看看