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

        }

    }

  • 相关阅读:
    order by子句
    having和where的区别
    O2O模式为什么这么火
    高德----------百度地图
    list后台转化为JSON的方法ajax
    ajax中后台string转json
    ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
    压缩文件解压
    个人作业3——个人总结(Alpha阶段)
    第08周-集合与泛型
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6357448.html
Copyright © 2011-2022 走看看