当前位置:网站首页>Leetcode 213: 打家劫舍 II
Leetcode 213: 打家劫舍 II
2022-07-03 07:21:00 【会学习的朱丫】
你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都 围成一圈 ,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警 。
给定一个代表每个房屋存放金额的非负整数数组,计算你 在不触动警报装置的情况下 ,今晚能够偷窃到的最高金额。

思路
这道题目和198.打家劫舍是差不多的,唯一区别就是成环了。
对于一个数组,成环的话主要有如下三种情况:
- 情况一:考虑不包含首尾元素

- 情况二:考虑包含首元素,不包含尾元素

- 情况三:考虑包含尾元素,不包含首元素

注意我这里用的是"考虑",例如情况三,虽然是考虑包含尾元素,但不一定要选尾部元素! 对于情况三,取nums[1] 和 nums[3]就是最大的。
而情况二 和 情况三 都包含了情况一了,所以只考虑情况二和情况三就可以了。
分析到这里,本题其实比较简单了。
class Solution {
public int rob(int[] nums) {
if (nums == null || nums.length == 0)
return 0;
int len = nums.length;
if (len == 1)
return nums[0];
if(len ==2)
return Math.max(nums[0],nums[1]);
return Math.max(robAction(nums, 0, len - 2), robAction(nums, 1, len-1));
}
int robAction(int[] nums, int start, int end) {
int first = nums[start], second = Math.max(nums[start], nums[start + 1]);
for (int i = start + 2; i <= end; i++) {
int temp = second;
second = Math.max(first + nums[i], second);
first = temp;
}
return second;
// int[] dp = new int[nums.length];
// dp[start] = nums[start];
// dp[start + 1] = Math.max(nums[start], nums[start + 1]);
// for (int i = start + 2; i <= end; i++) {
// dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]);
// }
// return dp[end];
}
}第一种方法可以省点内存。
边栏推荐
- Store WordPress media content on 4everland to complete decentralized storage
- Wireshark software usage
- Inno setup production and installation package
- PHP install the spool extension
- The difference between typescript let and VaR
- Margin left: -100% understanding in the Grail layout
- PHP install composer
- New stills of Lord of the rings: the ring of strength: the caster of the ring of strength appears
- Common problems in io streams
- JS monitors empty objects and empty references
猜你喜欢
随机推荐
Hash table, generic
La différence entre le let Typescript et le Var
twenty million two hundred and twenty thousand three hundred and nineteen
Deep learning parameter initialization (I) Xavier initialization with code
带你全流程,全方位的了解属于测试的软件事故
sharepoint 2007 versions
Jeecg request URL signature
Gridome + strapi + vercel + PM2 deployment case of [static site (3)]
Laravel frame step pit (I)
C WinForm framework
最全SQL与NoSQL优缺点对比
【已解决】SQLException: Invalid value for getInt() - ‘田鹏‘
SecureCRT取消Session记录的密码
Download address collection of various versions of devaexpress
Advanced API (multithreading 02)
Pat grade a real problem 1166
Custom generic structure
LeetCode
Arduino Serial系列函数 有关print read 的总结
Raspberry pie update tool chain









