LeetCode题库解答与分析——#198. 打家劫舍HouseRobber

你是一个专业的强盗,计划抢劫沿街的房屋。每间房都藏有一定的现金,阻止你抢劫他们的唯一的制约因素就是相邻的房屋有保安系统连接,如果两间相邻的房屋在同一晚上被闯入它会自动联系警方

给定一个代表每个房屋的金额的非负整数列表,确定你可以在没有提醒警方的情况下抢劫的最高金额。

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.

个人思路:

抢劫不能连续进行,因此会隔两间或三间进行抢劫,对每间房判断其两或三间前的钱数,取较多的与当前房屋的钱数相加,比较抢到最后两间房可抢到钱的数额,取最大值。

代码(JavaScript):

/**
 * @param {number[]} nums
 * @return {number}
 */
var rob = function(nums) {
    var length = nums.length;
    if(length==1){
        return nums[0];
    }
    else if(length==0){
        return 0;
    }
    var money = new Array(length);
    for(var i=0;i



你可能感兴趣的:(LeetCode)