leetcode------House Robber

标题: House Robber
通过率: 27.5%
难度: 简单

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.

动态规划:一个数组取数字,不能取相邻的数字,然后求能取出数字的最大和,用一个用一个长度问len+1的数组res去维护,位置是1的放num[0]

然后res[i]表示,到第i个房子时拿到的最大和是多少,

res[i]=max(res[i-1],res[i-2]+num[i-1])

表示到i时,如果取i说明i-1是不取的,那么就要把i-2位置的数加上num【i-1】数,如果不取i的数,就是说明取了i-1的数,那么到位置i时最大值等于i-1位置的最大值

直接看代码:

 1 public class Solution {
 2     public int rob(int[] num) {
 3         int len=num.length;
 4         if(len==0)return 0;
 5         if(len==1)return num[0];
 6         int [] res=new int[len+1];
 7         res[0]=0;
 8         res[1]=num[0];
 9         for(int i=2;i<len+1;i++){
10             res[i]=Math.max(res[i-1],res[i-2]+num[i-1]);
11         }
12         return res[len];
13         
14     }
15 }

 

posted @ 2015-04-03 21:03  pku_smile  阅读(221)  评论(0编辑  收藏  举报