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];
}
};
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];
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性