198. House Robber
2016-03-03 14:49
337 查看
Problem
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 itwill 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.
Solution
DP问题, 用dp[ i ] 表示到 i 为止 (包含 i ) 的最大值,那么有两个选择1)偷 i , 不偷 i -1 dp [ i - 2] + arr[ i ]
2) 不偷 i, i -1 偷不偷都行 dp[ i - 1 ]
两者取最大 dp [ i ] = max ( dp [ i - 2] + arr[ i ], dp[ i - 1 ] );
class Solution { public: int rob(vector<int>& nums) { const int N = nums.size(); if(N == 0) return 0; if(N == 1) return nums[0]; int num0 = nums[0], num1 = max(nums[0], nums[1]), num2 = num1; for( int i = 2; i < N; i++){ num2 = max(num1, num0 + nums[i]); num0 = num1; num1 = num2; } return num2; } };
相关文章推荐
- 基于Android中dp和px之间进行转换的实现代码
- Android中dip、dp、sp、pt和px的区别详解
- LFC1.0.0 版本发布
- Android px、dp、sp之间相互转换
- HP data protector软件学习1--基本角色与基本工作流程
- HP data protector软件学习2--软件组成与界面介绍
- android中像素单位dp、px、pt、sp的比较
- Android对px和dip进行尺寸转换的方法
- Android根据分辨率进行单位转换-(dp,sp转像素px)
- android 尺寸 dp,sp,px,dip,pt详解
- DP问题各种模型的状态转移方程
- POJ-1695-Magazine Delivery-dp
- nyoj-1216-整理图书-dp
- TYVJ1193 括号序列解题报告
- 对DP的一点感想
- TYVJ上一些DP的解题报告
- soj1005. Roll Playing Games
- 01背包问题
- LeetCode之Maximum Product Subarray
- DP Flow