zoukankan      html  css  js  c++  java
  • LeetCode198 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.

     这个题用动态规划。一条街上人家都有一定量的财产,如果有连着两家的东西被盗就会触发警报。如果你去偷一条街的东西,如何在不触发警报的情况下,得到更多的东西。求得动态公式就是:i是到i为止得到的最多的财产。那么取得方法就是,拿第i家和第i-2家的东西(dp[i-2]+nums[i]),或者不拿i家,拿i-1家的东西(dp[i-1)。比较哪个更多一些。

     1 public class HouseRobber198 {
     2     public int rob(int[] nums){
     3         if(nums == null || nums.length ==0){
     4             return 0;
     5         }
     6         
     7         int[] dp = new int[nums.length +1];
     8         dp[0] = 0;
     9         dp [1] = nums[0];
    10         
    11         for(int i = 2; i <=nums.length; i++){
    12             dp[i] = Math.max(dp[i-2]+nums[i-1], dp[i-1]);
    13         }
    14         
    15         return dp[nums.length];
    16     }
    17 }
  • 相关阅读:
    力扣算法题—091解码
    力扣算法题—090子集2
    力扣算法题—089格雷编码
    力扣算法题—088合并两个有序数组
    HDU 1509 Windows Message Queue
    HDU 1241 Oil Deposits
    HDU 1096 A+B for Input-Output Practice (VIII)
    HDU 1108 最小公倍数
    HDU 1106 排序
    HDU 1003 Max Sum * 最长递增子序列(求序列累加最大值)
  • 原文地址:https://www.cnblogs.com/hewx/p/4539744.html
Copyright © 2011-2022 走看看