LeetCode——House Robber
来源:互联网 发布:哪些淘宝服装质量好的 编辑:程序博客网 时间:2024/06/02 06:46
LeetCode——House Robber
# 198
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 @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.
这一题的目的是求一个非负数组中最大的子序列,注意不能有两个相邻的元素。这一题明显是动态规划的题目,不是很难,把dp公式写出来就好了。就是用一个dp数字记录到第i个元素为止的最大子序列。
- C++
class Solution {public: int rob(vector<int> &num) { if (num.size() <= 1) return num.empty() ? 0 : num[0]; vector<int> dp = {num[0], max(num[0], num[1])}; for (int i = 2; i < num.size(); ++i) { dp.push_back(max(num[i] + dp[i - 2], dp[i - 1])); } return dp.back(); }};
这里需要注意的是,对于vector的元素,输入还是使用push_back比较好,用直接赋值的话会出现问题,我尝试解决了下,发现反倒麻烦,没必要。直接用vector的函数就好了。常用的函数就那么几个,多用也就记得了。
还有一种思想,就是对奇偶元素分别进行处理。其实跟上面的dp是一样的,只不过是分别处理。
- C++
class Solution {public: int rob(vector<int> &num) { int a = 0, b = 0; for (int i = 0; i < num.size(); ++i) { if (i % 2 == 0) { a += num[i]; a = max(a, b); } else { b += num[i]; b = max(a, b); } } return max(a, b); }};
可以写的简洁一点。
- C++
class Solution {public: int rob(vector<int> &nums) { int a = 0, b = 0; for (int i = 0; i < nums.size(); ++i) { int m = a, n = b; a = n + nums[i]; b = max(m, n); } return max(a, b); }};
- LeetCode——House Robber
- LeetCode——House Robber
- LeetCode——House Robber
- LeetCode题解——House Robber III
- Leetcode——198. House Robber
- LeetCode198—House Robber
- leetcode——198——House Robber
- leetcode——213——House Robber II
- leetcode——337—— House Robber III
- LeetCode学习篇十四——House Robber
- 【dp】Leetcode House Robber&& House Robber II
- 【leetcode】House Robber && House Robber II
- LeetCode --- House Robber & House Robber II
- LeetCode198——House Robber
- Leetcode198——House Robber
- DP——House Robber
- Algorithms—198.House Robber
- LeetCode OJ House Robber
- Bash的别名 与 常用快捷键
- AWS ES2搭建Shadowsocks+开启Google TCP BBR加速 超详细教程!
- 【福利】成为专业程序员路上用到的各种优秀资料、神器及框架
- 1、java简单的基础知识
- 【Scikit-Learn 中文文档】支持向量机
- LeetCode——House Robber
- 深入理解LayoutInflater.inflate()
- 笔记:udacity计算机导论
- Android Studio学习1
- 适配器模式
- SpringBoot集成MyBatis
- Windows搭建Git服务器(gitblit)
- 牛客练习赛5 D题 next_permutation 函数的使用
- Spring 基本概念和 IOC