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];

        }

    }

  • 相关阅读:
    父div不会被子div撑高
    ie6兼容问题
    浏览器兼容性技巧
    css hack基本语法
    网站设置为灰色
    .net cookie跨域请求指定请求域名
    实体对象属性和值转为键值对Dictionary
    C#通过对象属性名修改值
    jQuery.noConflict()解决imgBox.js依赖jquery版本问题
    华为OJ之最长公共子序列
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6357448.html
Copyright © 2011-2022 走看看