题目:
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;
}