博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
198. House Robber Java Solutions
阅读量:4994 次
发布时间:2019-06-12

本文共 1383 字,大约阅读时间需要 4 分钟。

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.

Credits:

Special thanks to for adding this problem and creating all test cases. Also thanks to for adding additional test cases.

to see which companies asked this question

采用动态递归思想,创建一个结果数组res,每个下标i取到的最大值是:

 Math.max(res[i-2] + nums[i], res[i-1])

按照这个递推公式,res[res.length-1] 即为所求.

 

1 public class Solution { 2     public int rob(int[] nums) { 3         if(null == nums || nums.length == 0) return 0; 4         if(nums.length == 1) return nums[0]; 5         //if(nums.length == 2) return nums[0] > nums[1] ? nums[0] : nums[1]; 6         int[] res = new int[nums.length]; 7          8         res[0] = nums[0]; 9         res[1] = Math.max(nums[0] , nums[1]);10         for(int i = 2;i < res.length; i++){11             res[i] = Math.max(res[i-2]+nums[i],res[i-1]);12         }13         return res[res.length-1];14     }15 }

 

转载于:https://www.cnblogs.com/guoguolan/p/5450766.html

你可能感兴趣的文章
windows如何能在“运行”框输入名称就启动相应的软件
查看>>
修复反编译资源文件及批量修复程序源码
查看>>
CODEVS 1217 借教室
查看>>
VM ware 安装时候的一些坑和解决办法
查看>>
【原】最长上升子序列——动态规划
查看>>
26. Remove Duplicates from Sorted Array
查看>>
RN开发-Navigator
查看>>
innodb二进制文件相关的参数
查看>>
前谷歌高管给初入职场新人的14条忠告
查看>>
01-html介绍和head标签
查看>>
Python之Linux下的 virtualenv
查看>>
ASP.NET Web开发框架之三 报表开发
查看>>
大家好
查看>>
PHP文件上传类
查看>>
Python基础 --- 使用 dict 和 set
查看>>
仿迅雷播放器教程 -- 基于VLC的MFC播放器 (6)
查看>>
Python之数据结构基础
查看>>
WPF:如何高速更新Model中的属性
查看>>
hdu 1010(DFS) 骨头的诱惑
查看>>
(转)Android SDK Manager国内无法更新的解决方案
查看>>