算法系列——House Robber
来源:互联网 发布:天刀怎样下载捏脸数据 编辑:程序博客网 时间:2024/06/01 07:47
题目描述
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.
解题思路
递归+记忆化搜索
可以采用递归方法+记忆化搜索的方案,尝试抢劫当前房子i和和下个房子i+2,不断更新Max值,同时采用记忆数组 保存中间计算值。
动态规划
思路:因为不能抢劫挨着的店家, 所以这道题的本质相当于在一列数组中取出一个或多个不相邻数,使其和最大,使用动态规划。 举例子{1,2,3,4}, f[i]表示到第i家能偷窃的最大钱数,f[0] = nums[0], f[1] = max(nums[0], nums[1]), f[2]有两种可能,就是只取f[1]或者取f[0] + f[2]. 所以递推公式是:
f[i] = Math.max(f[i - 2] + nums[i], f[i - 1]);
时间复杂度: O(n)
空间复杂度: O(n)
程序实现
递归+记忆化搜索
class Solution { //记忆数组 private int[] memo; public int rob(int[] nums) { memo=new int[nums.length]; Arrays.fill(memo,-1); return tryRob(nums,0); } private int tryRob(int[] nums,int index){ if(index>=nums.length) return 0; if(memo[index]!=-1) return memo[index]; int res=0; for(int i=index;i<nums.length;i++) res=Math.max(res,nums[i]+tryRob(nums,i+2)); memo[index]=res; return res; }}
动态规划
class Solution { public int rob(int[] nums) { if(nums==null||nums.length==0) return 0; int n=nums.length; int []dp=new int[n]; dp[0]=nums[0]; if(n==1) return dp[0]; dp[1]=Math.max(nums[0],nums[1]); for(int i=2;i<n;i++) dp[i]=Math.max(dp[i-2]+nums[i],dp[i-1]); return dp[n-1]; }}
- 算法系列——House Robber
- LeetCode198—House Robber
- 算法题——House Robber(JAVA)
- Leetcode House Robber系列
- LeetCode:House Robber系列
- Leetcode: House Robber 系列
- LeetCode——House Robber
- LeetCode198——House Robber
- LeetCode——House Robber
- Leetcode198——House Robber
- DP——House Robber
- LeetCode——House Robber
- Algorithms—198.House Robber
- Leetcode House Robber 系列总结
- LeetCode213——House Robber II
- LeetCode题解——House Robber III
- 每日一练——House Robber
- House Robber III——Difficulty:Medium
- andriod返回时刷新上一级activity实现
- traceroute和tracert区别
- 智能聊天机器人小黄鸡及其制作方法
- hdu1255 覆盖的面积(线段树+离散化+扫描线)
- SQL:oracle 层次查询 start with connect by
- 算法系列——House Robber
- redis的相关操作和命令
- poj 3468 区间修改查询 解题报告
- 去除数组中重复的对象
- 欢迎使用CSDN-markdown编辑器
- git命令总结
- 关于Kinectv2的一些资料
- 【干货】重度Chrome控推荐自用插件
- C++中拷贝构造函数、浅拷贝与深拷贝的详解