Leetcode - House Robber

来源:互联网 发布:飞思卡尔单片机怎么学 编辑:程序博客网 时间:2024/06/14 23:42

Question

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.


Java Code

/** * 动态规划问题: *      某个街区有一排相连的house,其序号为数组的下标, *      每个house里放有确定数额的money,即数组中的元素值, *      现有一职业小偷准备洗劫这个街区,问他能够偷到的最多金额。 *      要求:不能偷相邻的house,否则会触发警报! * 解题思路: *      由于不能偷相邻的房间,所以小偷至少每隔1个房间偷一次, *      寻找递推关系,给出每个房间处小偷能够偷到的最大金额。 *      分析得知,小偷经过当前房间时可能偷也可能不偷,进一步分析: *      1. 如果不偷当前房间,必定是因为已经偷了前一个房间(前一个房间不偷行不行?), *      所以此时的最大金额就等于偷完前一个房间之后的金额 *      2. 如果偷当前房间,则前一个房间必定没偷过(那前前一个房间有没有偷过呢?), *      所以此时的最大金额就等于小偷在前前一个房间处已经得到的最大金额加上当前房间的money *  * @author 漫游者 */    public int rob(int[] nums) {       int len = nums.length;       int[] sumMoney = new int[len];       if(len == 0) return 0;       sumMoney[0] = nums[0];       if(len == 1) return sumMoney[0];       sumMoney[1] = Math.max(nums[0], nums[1]);       if(len == 2) return sumMoney[1];       for(int i = 2; i < len; ++i)           sumMoney[i] = Math.max(sumMoney[i-1], sumMoney[i-2] + nums[i]);       return sumMoney[len-1];   }
0 0
原创粉丝点击