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

        }

    }

  • 相关阅读:
    go相关
    mac下使用vscode技巧
    mac下secureCRT的使用技巧
    python subprocess实时输出
    python中多级目录导入模块问题
    python的print与sys.stdout
    python中类相关笔记
    python中sys.stdout.flush()的作用
    nginx+uwsgi配置
    虚拟机的 基本配置
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6357448.html
Copyright © 2011-2022 走看看