LeetCode-难题集之House_Robber系列
来源:互联网 发布:重庆市网络办事大厅 编辑:程序博客网 时间:2024/05/16 00:27
记——House_Robber,这个系列的题的思路也很简单,不过大神的代码就是给力,因此记下留着以后学习参考。
House_Robber
class Solution {public: int rob(vector<int>& nums) {nums.insert (nums.begin(),2,0);int n = nums.size();vector<int> opt(n,0);for(int i=2;i<n;++i){opt[i]=max(opt[i-1],opt[i-2]+nums[i]);}return opt[n-1]; }};//大神的代码是我的版本的更简化,学习学习class Solution {public: int rob(vector<int>& nums) { int it1 = 0, it2 = 0; for (int i = 0; i < nums.size(); i++) { it1 = max(it1 + nums[i], it2); swap(it1, it2); } return it2; }};
House_Robber2
//我去,思路这么简单,我还想了半天class Solution {public: int rob(vector<int>& nums) { int n = nums.size(); if (n < 2) return n ? nums[0] : 0; return max(robber(nums, 0, n - 1), robber(nums, 1, n)); }private: int robber(vector<int>& nums, int l, int r) { int pre = 0, cur = 0; for (int i = l; i < r; i++) { int temp = max(pre + nums[i], cur); pre = cur; cur = temp; } return cur; }};
House_Robber3
class Solution {//知道用递归,但是没有想到这么处理,恩,向大神学习。public: /* a / \ b c Consider above case, at leaf rob_with_root = root_val+max_left_wo_root + max_right_wo_root rob_without_root = max(max_left_with_root, max_left_wo_root) + max(max_right_with_root, max_right_wo_root) max_rob = std::max(rob_with_root, rob_without_root); */ void dp(TreeNode* root, int& rob_with_root, int& rob_without_root) { if (nullptr == root) { rob_with_root = 0; rob_without_root = 0; return; } int max_left_wo_root=0; int max_right_wo_root=0; int max_left_with_root=0; int max_right_with_root=0; dp(root->left, max_left_with_root, max_left_wo_root); dp(root->right, max_right_with_root, max_right_wo_root); rob_with_root = root->val + max_left_wo_root + max_right_wo_root; rob_without_root = std::max(max_left_with_root, max_left_wo_root) + std::max(max_right_with_root, max_right_wo_root); } int rob(TreeNode* root) { int root_val=0; int children_val=0; dp(root, root_val, children_val); return std::max(root_val, children_val); }};
0 0
- LeetCode-难题集之House_Robber系列
- LeetCode-难题集之Best_Time_to_Buy_and_Sell_Stock系列
- LeetCode-难题集之Sudoku_Solver
- LeetCode-难题集之Merge Two Sorted Lists
- LeetCode-难题集之Implement strStr()与KMP算法
- LeetCode-难题集之Linked List Random Node
- Leetcode之remove系列
- 不容易系列之(3)—— LELE的RPG难题
- 不容易系列之(3)—— LELE的RPG难题
- 不容易系列之(3)—— LELE的RPG难题
- 不容易系列之(3)—— LELE的RPG难题
- 不容易系列之(3)—— LELE的RPG难题
- 不容易系列之(3)—— LELE的RPG难题
- 不容易系列之(3)—— LELE的RPG难题
- 不容易系列之(3)—— LELE的RPG难题
- 不容易系列之(3)—— LELE的RPG难题
- 不容易系列之(3)—— LELE的RPG难题
- 不容易系列之(3)—— LELE的RPG难题
- 计算几何基本模板
- 【HDU】2199 - Can you solve this equation?(二分)
- POJ 1088 经典动态规划(记忆搜索)问题
- java正则表达式的分组
- hadoop:基于Streaming实现的编译
- LeetCode-难题集之House_Robber系列
- actionscript3.0 数组排序
- openstack service port(服务端口)
- 解析STM32的启动过程及STM32 启动文件选择
- 二叉树中和为某一值的路径
- Top K 算法详解
- JAVA 容器类
- jmeter压力测试
- iOS加密算法(base64,md5,HMAC,3DES,AES 256,RSA)