leetcode--House Robber
来源:互联网 发布:淘宝的运费险是什么意思 编辑:程序博客网 时间:2024/05/17 07:51
题目: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.
分析:本质是在一列数组中取出一个或多个不相邻数,使其和最大。一般使用动态规划的方法。方法分为使用一种数组或两个变量或分奇偶
One:基于数组的DP:
public class Solution { public int rob(int[] nums) { if(nums.length <= 1)return nums.length==1 ? nums[0] : 0; int len = nums.length; int[] dp = new int[len]; dp[0] = nums[0]; dp[1] = Math.max(nums[0],nums[1]); for(int i=2;i<len;++i){ dp[i] = Math.max(nums[i]+dp[i-2],dp[i-1]); } return dp[len-1]; }}Two:基于两个数的DP--奇偶保证两数不相邻
public class Solution { public int rob(int[] nums) { int a = 0,b = 0; for(int i=0;i<nums.length;++i){ if(i%2==0){ a += nums[i]; a = Math.max(a,b);//偶数的dp }else{ b += nums[i]; //上上dp+nums[i] b = Math.max(a,b);//奇数的dp } } return Math.max(a,b); }}
Three:更简化
public class Solution { public int rob(int[] nums) { int a = 0,b = 0; for(int i=0;i<nums.length;++i){ int m = a,n = b;//n为上上一个dp m为上上上个dp+num[i-1] a = nums[i] + n; //上上dp+nums[i] b = Math.max(n,m);//m上上上个dp+nums[i-1]和n上上dp的上dp } return Math.max(a,b); }}
0 0
- 【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
- 谈区块链技术在积分领域的应用
- Android OkHttp完全解析 是时候来了解OkHttp了
- findbugs,PDM,CheckStyle各自的检查项
- Hmm 问题待解决
- java中自动装箱和自动拆箱
- leetcode--House Robber
- 距春节仅剩不到五十天的时间,建议提前安排行程,做好抢票准备
- ffmpeg+opencv播放器
- 初识android动画(2)之补间动画
- bash vim mode
- SpringMVC深度探险 —— DispatcherServlet与初始化主线
- Android studio在代码中跳转下一行快捷键
- 1622-5 孔富晨 总结《2016年12月11日》 【连续第72天总结】
- 实战将用户的权限一次性拿出来