Leetcode14: House Robber
来源:互联网 发布:cf手游外卦软件 编辑:程序博客网 时间:2024/06/05 03:08
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.
简单归纳起来就是说一个数组,取若干个数出来,使得总和最大,前提是这些数在数组中不能是相邻的。
假设dp[i]为在长度为i的数组之前我已经得到的最大值,这个最大值要么取到了num[i]要么没取到num[i]。那么递推的表达式其实就是dp[i]=max(dp[i-1], dp[i-2]+num[i]);初始条件dp[0]=num[0],dp[1]=max(dp[0], num[1])。
class Solution {public: int rob(vector<int> &num) { int n = num.size(); vector<int> dp(n); if(n == 0) return 0; dp[0] = num[0]; dp[1] = max(dp[0], num[1]); for(int i = 2; i < n; i++) { dp[i] = max(dp[i-1], dp[i-2]+num[i]); } return dp[n-1]; }};
- Leetcode14: House Robber
- House Robber
- House Robber
- House Robber
- House Robber
- House Robber
- House Robber
- House Robber
- House Robber
- House Robber
- House Robber
- House Robber
- House Robber
- House Robber
- House Robber
- House Robber
- House Robber
- House Robber
- shell编程之变量
- 基于ARM11的无线视频监控系统
- 为GridView添加HeaderView
- 删除注册表中USB VID痕迹方法
- CMAKE安装最新版本
- Leetcode14: House Robber
- 项目里需要在服务启动时进行一些业务逻辑
- 怎么样使用yum来安装mysql和远程访问
- 欢迎使用CSDN-markdown编辑器
- 如何在Windows下使用Linux系统来编译和运行程序?
- Linux系统优化思路
- cache一致性问题的一个现象
- 多线程的通信方法
- POJ 3617 Best Cow Line