Leetcode 198. House Robber

本文针对LeetCode上的“打家劫舍”问题提供了解决方案,使用动态规划方法来确定在不触动相邻房屋警报的情况下,能从这些房屋中抢夺的最大金额。

题目链接:https://leetcode.com/problems/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.

解析:先搞懂题意:也就是说不能偷连续的两家,用动态规划的思想,动态规划关键要找到递推公式,要学会分析,对于第i家要么偷要么不偷,到第i家,偷的最多的钱有两种可能:

偷第i家,那么不能偷i-1家,money[i][1]=money[i-1][0]+nums[i]

不偷第i家,那么i-1家可以偷也可以不偷,money[i][0]=max{money[i-1][1],money[i-1][0]}

动态规划题重要的是思路,是递推公式!!!如何把问题分解为小问题!!!需要多做!!!总是没思路。。。

代码:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值