House Robber
2015-06-25 11:16
232 查看
Description:
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.
Code:
令f(n)表示从1号房子到n号房子可以偷到的最大钱数,则:
f(n)=max(f(n-1), f(n-2)+an)
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.
Code:
int rob(vector<int>& nums) { if (nums.empty()) return 0; size_t length = nums.size(); int result = 0; if (1==length) return nums[0]; else if (2==length) return (nums[0]>=nums[1])?nums[0]:nums[1]; else { int p = nums[0], q=(nums[0]>=nums[1])?nums[0]:nums[1]; for (int i = 2; i <= length-1; ++i) { int temp = p+nums[i]; result=(temp>=q)?temp:q; p = q; q = result; } } return result; }
令f(n)表示从1号房子到n号房子可以偷到的最大钱数,则:
f(n)=max(f(n-1), f(n-2)+an)
相关文章推荐
- Linux中特殊权限--suid、guid
- jqGrid表格之自定义subGrid
- Access restriction: The type TelnetOutputStream is not accessible due to restric
- 按层次遍历二元树
- Android事件机制之一:事件传递和消费
- android瀑布流简单实现原理
- Joomla添加分类和文章时的目录数据结构
- cocos js update()
- 【转】windows上自动设置java环境变量的脚本
- 百度文库 - PS
- django使用group by
- java垃圾回收机制
- 随心摘录(1)
- JavaScript学习之变量类型
- struct和typedef struct
- 《Java程序设计》第16周周四:GUI编程及文件对话框的使用
- stringstream的用法
- Python - Timer Threads
- http协议详解
- SQL语句实现根据经纬度计算距离并排序分页