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

        }

    }

  • 相关阅读:
    [noip2018]day1
    [CF1110d]JONGMAH
    BZOJ 2733 [HNOI2012]永无乡
    BZOJ 3123 [SDOI2013] 森林
    Nowcoder 练习赛26E 树上路径
    Luogu 2575 高手过招-SG函数
    BZOJ 1123[POI2008]BLO-Tarjan
    Nowcoder OI赛制测试2 F 假的数学题
    Luogu 2467[SDOI2010]地精部落
    Luogu 2216[HAOI2007]理想的正方形
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6357448.html
Copyright © 2011-2022 走看看