House Robber(leetcode)
来源:互联网 发布:linux执行sh文件命令 编辑:程序博客网 时间:2024/06/02 02:07
原题如下:
You are aprofessional robber planning to rob houses along a street. Each house has acertain amount of money stashed, the only constraint stopping you from robbingeach of them is that adjacent houses have security system connected and it willautomatically contact the police if two adjacent houses were broken into on thesame night.
Given a list ofnon-negative integers representing the amount of money of each house, determinethe maximum amount of money you can rob tonight without alerting the police.
解题思路:这道题目乍一看还是挺麻烦的,说到底,就是找出一个数组中前n项中所有不相邻项数的和的最大值,这个如果用普通的方法还是挺麻烦的。这里我们考虑使用动态规划,假如我们想要求数组num前n项中所有不相邻项的和的最大值(其中必须有num(n))max(n),要么max(n)=max(n-2)+num(n),要么max(n)=max(n-3)+num(n),当然,n=1,2,3的情况要单独拿出来考虑,最后将数组中所有项对应的max值都算出来,然后就是比较max(n-1)与max(n)的大小了,返回较大的那一个即可。
算法:
1、 定义一个临时数组max(n,0),n为数组num的大小,max(i)代表前i项中包括num(i)的不相邻的项的和的最大值;
2、 先处理单个情况,当i=0,1,2时,单独求出max(i);
3、 当i>=3时,max(i)为max(i-2)+num(i)和max(i-3)+num(i)中较大的那一个。
4、 最后结果:当n=1,时,返回max(n-1)即可;否则,返回max(n-1)和max(n-2)中较大的那一个。
算法复杂度分析:整个函数只用了一层循环用来求各项的max,所以算法复杂度为O(n)。
具体代码如下:
class Solution {
public:
int rob(vector<int>& nums) {
int n=nums.size();
if(n==0)return 0;
vector<int> max(n,0);
for(int i=0;i<n;++i){
if(i==0||i==1)max[i]=nums[i];
elseif(i==2)max[i]+=max[i-2]+nums[i];
else{
if(max[i-2]>max[i-3])
max[i]+=nums[i]+max[i-2];
else
max[i]+=nums[i]+max[i-3];
}
}
if(n==1)return max[n-1];
if(max[n-1]>max[n-2])returnmax[n-1];
return max[n-2];
}
};
- 【dp】Leetcode House Robber&& House Robber II
- 【leetcode】House Robber && House Robber II
- LeetCode --- House Robber & House Robber II
- LeetCode OJ House Robber
- Leetcode: House Robber
- Leetcode 198: House Robber
- House Robber - LeetCode
- LeetCode 之 House Robber
- leetcode--House Robber
- [leetcode]47 House Robber
- [LeetCode] House Robber
- LeetCode :House Robber
- [leetcode] House Robber
- [leetcode]House Robber
- [LeetCode]198.House Robber
- LeetCode House Robber题解
- leetcode:House Robber
- [LeetCode]House Robber
- OpenCV findContours函数时的小发现
- 如何用Azure Web App Services接入微信公众号
- Latex插入编号
- JSPatch库, 一个Apple官方支持的实现在线更新iOS应用的库
- 二进制数转换成十进制数(栈来实现)
- House Robber(leetcode)
- webView访问HTTPS
- JSONP原理优缺点(只能GET不支持POST)
- 安卓踩过的坑
- ubuntu环境变量的相关问题
- C++“准”标准库Boost学习指南(3):Boost.Utility
- 百度地图导航初始化失败问题总结
- Mac下解决SVN:155036
- 括号匹配