LeetCode-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.


翻译:

你是一个专业的强盗预谋抢劫一排路边上的房子。每个房子都有一定数量的钱可以偷盗,但是你不能挨家挨户去偷盗因为每两个相邻的房子连接了安全系统。一旦你在同一个晚上偷盗了两个相邻的房子,那么安全警报就会自动向警察报警。

给定一个含有非负数的数组表示每个房子含有的钱数,确定在不惊动警察的前提下你能偷到的最大金额的钱。


思路:

假设nums=[3,4,5,1,7]表示了当前街道上每一户人家分别含有的钱数,开辟一个新的数组dp用来表示偷到第 i 家时,当前收获的最大金额。那么dp[0]=3为偷到第0家时可以偷到3;因为nums[1]=4>nums[0]=3,因此,dp[1]=4,即偷到第1家时最大偷到4而不偷第0家;继续向后计算dp时,比较nums[i]+dp[i-2]和dp[i-1],因为不能偷取相邻的,所以如果选择偷当前家,那么就要和dp[i-2]相加与是否偷取上一家的结果dp[i-1]比较挑选大的作为dp[i]。


C++代码(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

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

int main()
{
	Solution s;
	vector<int> nums = {3,4,5,1,7};
	int result;
	result = s.rob(nums);
	cout << result;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值