您的位置:首页 > 编程语言 > C语言/C++

House Robber

2016-05-17 19:27 316 查看
题目描述:

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.
解题思路:使用动态规划,d[i]表示盗窃从0到i的houses能获得的最大的money。状态转移方程为:d[i]=max(nums[i]+d[i-2],d[i-1])
AC代码如下:

class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0;
if (n == 1) return nums[0];
vector<int> d(n, 0);
d[0] = nums[0];
d[1] = max(nums[0], nums[1]);
for (int i = 2; i < n; ++i){
d[i] = max(nums[i] + d[i - 2], d[i - 1]);
}
return d[n - 1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode C++ House Robber