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)
  • 相关阅读:
    sqlserver 表操作 SQL篇
    C#知识点汇总
    DDL
    sqlserver2008简介
    面向对象继承
    IO文件流
    【帅刺猬课堂】Winform中使用WPF的UserControl
    KS Gantt甘特图控件通过递归加载无限层级的数据
    Office 每次打开需要重新配置的问题修复方法
    扩展方法
  • 原文地址:https://www.cnblogs.com/acetseng/p/4656507.html
Copyright © 2011-2022 走看看