leetCode#198. House Robber
来源:互联网 发布:防网络诈骗图片 编辑:程序博客网 时间:2024/06/16 06:10
Description
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.
Code
class Solution(object): def rob(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 if len(nums) == 1: return nums[0] if len(nums) == 2: return max(nums[0], nums[1]) if len(nums) == 3: return max(nums[1], nums[0] + nums[2]) return max(nums[0] + self.rob(nums[2:]), nums[1] + self.rob(nums[3:]))
这个没有通过时间检测,不过思路很清晰了,就是遍历。
别人的代码:
#define max(a, b) ((a)>(b)?(a):(b))int rob(int num[], int n) { int a = 0; int b = 0; for (int i=0; i<n; i++) { if (i%2==0) { a = max(a+num[i], b); } else { b = max(a, b+num[i]); } } return max(a, b);}
class Solution {public: int rob(vector<int>& nums) { int n = nums.size(), pre = 0, cur = 0; for (int i = 0; i < n; i++) { int temp = max(pre + nums[i], cur); pre = cur; cur = temp; } return cur; }};
f(0) = nums[0]
f(1) = max(num[0], num[1])
f(k) = max( f(k-2) + nums[k], f(k-1) )
执行的就是这个公式。感觉得死记了,自己并没有很好的理解这题的思路。
阅读全文
0 0
- [LeetCode]198.House Robber
- 【LeetCode】198. House Robber
- 【LeetCode】198.House Robber
- LeetCode 198. House Robber
- [leetcode] 198.House Robber
- [leetcode] 198. House Robber
- LeetCode:198. House Robber
- 198. House Robber LeetCode
- [LeetCode]198. House Robber
- LeetCode || 198. House Robber
- LeetCode-198. House Robber
- [LeetCode]198. House Robber
- 【LeetCode】198. House Robber
- LeetCode#198. House Robber
- LeetCode 198. House Robber
- leetcode 198. House Robber
- LeetCode *** 198. House Robber
- leetcode 198. House Robber
- python中os.path以及sys.path模块简介
- java 操作数字证书(x509)
- springmvc中controller 使用@RestController 和 @Controller 返回结果的区别
- 【数据挖掘 xgboost】特征的重要程度分析
- Maven使用中相关的问题
- leetCode#198. House Robber
- JVM之类文件结构
- IntelliJ IDEA添加jar包
- 我为什么使用maven
- GitHub最著名的20个Python机器学习项目!
- 【阿里在线技术峰会】何登成:AliSQL性能优化与功能突破的演进之路
- JSONDecodeError: Expecting value: line 1 column 1 (char 0)
- PrintWriter用法简析
- 购物车删除 筛选 排序