标签:
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。(不要问我为什么是纯手工打造。。)
标签:
原文地址:http://www.cnblogs.com/acetseng/p/4656507.html