leetcode-198-线性DP-打家劫舍 发表于 2020-04-21 | 分类于 数据结构与算法 题目 解法1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950// 递归 + 备忘录class Solution {public: int rob(vector<int>& nums) { if(nums.empty()) return 0; vector<int> memo(nums.size(), -1); return helper(nums, 0, memo); } // 从索引start开始偷取获得的最大利润 int helper(vector<int> &nums, int start, vector<int> &memo){ if(start >= nums.size()) return 0; if(memo[start] != -1) return memo[start]; int res = max(nums[start] + helper(nums, start+2, memo), helper(nums, start+1, memo)); memo[start] = res; return res; }};// 动态规划class Solution {public: int rob(vector<int>& nums) { if(nums.empty()) return 0; // memo[i] = x 表示从第i间房子开始抢劫,最大收益为x vector<int> memo(nums.size()+2, 0); for(int i = nums.size()-1; i >= 0; --i){ memo[i] = max(nums[i] + memo[i+2], memo[i+1]); } return memo[0]; }};// 动态规划,优化空间复杂度class Solution {public: int rob(vector<int>& nums) { if(nums.empty()) return 0; int memo_i_1 = 0, memo_i_2 = 0; int memo_i = 0; for(int i = nums.size()-1; i >= 0; --i){ memo_i = max(nums[i] + memo_i_2, memo_i_1); memo_i_2 = memo_i_1; memo_i_1 = memo_i; } return memo_i; }};