Leetcode-198. House Robber

本文探讨了一位专业抢劫者如何在不触发相邻警报系统的前提下,实现最大金额的盗窃。通过分析给定的房屋金额列表,提出了一种策略来确定最优的盗窃计划,确保不会触发相邻房屋的报警系统。该策略的核心在于比较当前选择与前两步的选择,以决定是否采取当前房屋作为目标。

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.

给出一个vector,不能连续的两个vector相加,求最后这样的一个vector的最大加和返回值。

关键思路是:当前点 i 与 第 i - 2 个的产出结果的值相加,能否大于 第 i - 1 个的产出结果,要是大于的话,就采用此策略,即第 i 点被采纳加入,若不行,则采用 第 i -1 个的产出结果作为第 i 的产出结果。

本题主要参考:http://www.cnblogs.com/ganganloveu/p/4417485.html

结果代码:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值