zoukankan      html  css  js  c++  java
  • LeetCode#198 House Robber

    Problem Definition:

    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.

    Solution:

    1_如果数组中没有数,得0;

    2_如果只有一个数 i, 选它得 i, 不选它得0;

    3_如果有两个数 i,j(按顺序出现)选 j 得 j, 选 i,得 i;

    4_如果有三个数 i, j, k, 选 k 则不能选 j, 得 i+k、不选 k 得 max( i, j);

    ......

    发现每次选择都面临两种可能:A.选取当前值 (最尾的值);B.不选取当前值。

    如果从第一个数出发,递推关系如下:

      1) 上次不取最尾值所得到的最大和+本次的最尾值==>本次取最尾值所能得到的最大和

      2)max(上次取最尾值所得最大和,上次不取最尾值所得最大和)==>本次不取最尾值所能得到的最大和

    晕不...

    那来看个栗子吧:

      图中第一行是数组,第二行是情况A,第三行是情况B。(不要问我为什么是纯手工打造。。)

    代码:

     1 def rob(nums):
     2         if nums==[]:
     3             return 0
     4         d1=0
     5         d2=nums[0]
     6         nums.pop(0)
     7         for i in nums:
     8             tmp=d2
     9             d2=d1+i
    10             d1=max(d1,tmp)
    11         return max(d1,d2)
  • 相关阅读:
    解决:Android 8.0检测不到当前的activity
    flask学习(十三):过滤器
    打开相册上传图片
    完整的项目
    解决ScrollView滑动RecyclerView的卡顿
    RxJava
    CoordinatorLayout
    NestedScrollView,RecyclerView
    ViewPageIndicator
    RxJava的实现原理
  • 原文地址:https://www.cnblogs.com/acetseng/p/4656507.html
Copyright © 2011-2022 走看看