[leetcode]打家劫舍(House Robber)

打家劫舍(House Robber)

你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警

给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。

示例 1:

输入: [1,2,3,1]
输出: 4
解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
     偷窃到的最高金额 = 1 + 3 = 4 。

示例 2:

输入: [2,7,9,3,1]
输出: 12
解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。
     偷窃到的最高金额 = 2 + 9 + 1 = 12 。

原题链接:https://leetcode-cn.com/problems/house-robber/

题解:

class Solution {
public:
    int rob(vector<int>& nums) {
        int len = nums.size();
        vector<int> a(len+3);
        if(len==0)
            return NULL;
        a[0]=nums[0];
        a[1]=max(nums[0],nums[1]) ;
        for(int i=2; i<len;i++)
    {
             a[i] = (nums[i] +a[i-2])>a[i-1] ?(nums[i] +a[i-2]):a[i-1];
    }
        if(nums.size()==1) 
            return a[0] ;
        else
            return a[len-1];

    }
};

选第 i个房间则a[i] = nums[i] + a[i-2] 不选第i个房间则a[i] = a[i-1]

最后的最优解即判断a[i]和a[i-1]哪个大

猜你喜欢

转载自blog.csdn.net/gcn_Raymond/article/details/84779570