198. House Robber
来源:互联网 发布:excel表格数据合并计算 编辑:程序博客网 时间:2024/06/14 00:32
198. House Robber
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.
分析:一组数的选择性求和,条件就是相邻的两个数不能取。
解法1:定义sum[i]是对前i个房子抢劫,所能得到的最大数。递推式:
sum[i]=max(sum[i-1],sum[i-2]+nums[i]);即根据第i个房子是否被抢劫分成两种情况,去抢则是nums[i]+sum[i-2],不抢则是sum[i-1]。
int rob(vector<int>& nums) { int n=nums.size(); if(n==0) return 0; if(n==1) return nums[0]; vector<int> sum(n); sum[0]=nums[0]; sum[1]=max(nums[0],nums[1]); for(int i=2;i<n;i++) { sum[i]=sum[i-1]; if(sum[i]<sum[i-2]+nums[i]) sum[i]=sum[i-2]+nums[i]; } return sum[n-1]; }时间复杂度: O(n) 空间复杂度: O(n)
解法2:
对于每个房子只有两种状态,抢与不抢;抢劫到第i-1次时,有两个状态include和exclude,分别表示抢了与未抢;进行到第i次是,include更新为第i-1次的exclude加上num;exclude取前一次的exclude和该次exclude(也就是上次的include)的较大者。
因为求和的约束是,当前取了num,那么它的前一次状态必是exclude。
int rob(vector<int>& nums) { int n=nums.size(); int include=0,exclude=0; for(int num:nums) { int i=include,e=exclude; include=e+num; exclude=max(e,i); } return max(include,exclude); }时间复杂度:O(n) 空间复杂度:O(1)
最后,对动态规划问题有了不同的柑橘,从状态的角度分析问题,就想解法2的思路。当前问题的求解,只依赖于前一次的不同状态,这时可以降低空间复杂度,理解也更透彻。还很模糊,要加深理解。
- 337. House Robber III+198. House Robber
- 198. House Robber&&213. House Robber II
- 198. House Robber && 213. House Robber II
- [LeetCode]198.House Robber
- 【LeetCode】198. House Robber
- 【LeetCode】198.House Robber
- LeetCode 198. House Robber
- 198.House Robber
- [leetcode] 198.House Robber
- [leetcode] 198. House Robber
- LeetCode:198. House Robber
- 198. House Robber LeetCode
- 198. House Robber
- [LeetCode]198. House Robber
- 198. House Robber
- LeetCode || 198. House Robber
- 198. House Robber
- LeetCode-198. House Robber
- JVM Internals
- 2016/10/26 c语言tcp传输文件的理解
- java中的匿名内部类总结
- PostgresSql 中查询库中全部的表
- 深入解析C++编程中的静态成员函数
- 198. House Robber
- FF&Chrome中的AJAX
- 关于recycleView
- think in java笔记: Thread的interrupt()方法
- hellocharts使用流程
- bzoj2763飞行路线(dijkstra和SPFA两个版本)
- android实现颜色渐变
- R语言:spdep包(空间数据分析与R语言实践)
- 欢迎使用CSDN-markdown编辑器