[LeetCode]198. House Robber I&II
来源:互联网 发布:json日期格式化输出 编辑:程序博客网 时间:2024/05/22 08:22
https://leetcode.com/problems/house-robber/
显然空间复杂度O(1)的DP问题。rob和notRob记录当前位置抢或者不抢所能获得的最大收益。当前未抢 = max(上次抢了,上次未抢);当前抢了 = 上次未抢 + 当前价值
public class Solution { public int rob(int[] nums) { if (nums == null) { return 0; } int rob = 0; int notRob = 0; for (int n : nums) { int curNotRob = notRob; notRob = Math.max(notRob, rob); rob = curNotRob + n; } return Math.max(rob, notRob); }}
https://leetcode.com/problems/house-robber-ii/
如果数组成环。
那么首尾两个只能最多取一个,因此结果为1 ~ len - 1 和 0 ~ len - 2里面较大的那个
public class Solution { public int rob(int[] nums) { if (nums == null || nums.length == 0) { return 0; } return Math.max(rob(nums, 0, nums.length - 2), rob(nums, 1, nums.length - 1)); } private int rob(int[] nums, int beg, int end) { if (nums.length == 1) { return nums[0]; } int notRob = 0; int rob = 0; for (int i = beg; i <= end; i++) { int curNotRob = Math.max(notRob, rob); rob = notRob + nums[i]; notRob = curNotRob; } return Math.max(rob, notRob); }}
0 0
- [LeetCode]198. House Robber I&II
- 【leetcode】House Robber I && II
- House Robber I & II | LeetCode
- leetcode House Robber I II
- 【LeetCode】House Robber I & II 解题报告
- LeetCode House Robber I and II
- LeetCode House Robber I II III
- leetcode(198,213)House Robber(I,II)
- 【LeetCode】House Robber I,II,III解析
- [leetcode] House Robber [i ii iii]
- Leetcode-198. House Robber,213. House Robber II
- LeetCode 198. House Robber 213. House Robber II--动态规划
- LeetCode House Robber II
- [LeetCode] House Robber II
- [leetcode] House Robber II
- 【leetcode】House Robber II
- Leetcode: House Robber II
- leetcode House Robber II
- linux初始配置
- 2016php开发总结
- input 输入
- WIN下C++多人聊天下
- C++14尝鲜:constexpr函数(编译期函数)
- [LeetCode]198. House Robber I&II
- R语言:文本(字符串)处理与正则表达式
- 我眼中的光明·第二周
- 弹幕简单实现
- Android小白成长日记 1.我的第一个HelloWorld程序
- PAT-B 1063. 计算谱半径
- OC中NSValue使用
- 寒假思雨姐摸底A题,题解
- 【NOIP2014八校联考第2场第2试】帮助Bsny