当前位置: 代码迷 >> 综合 >> leetcode 198: House Robber
  详细解决方案

leetcode 198: House Robber

热度:52   发布时间:2023-12-18 00:37:53.0

问题描述:

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.

思路:

这个问题一开始我是觉得很像是递归解决的,于是采用最直接的方法,每求一个节点 k,都考虑求 k+1,k+2 两者之间最大值,以此类推。于是有代码一。

但是提交后发现是 Time Limit Exceeded,看来不能偷懒做少事儿啊。

上面方法相当于是树结构的由高层到底层,抽象递归;于是又想到从底层到高层,如当前计算节点 k 的目标值,只使用排列在自己之前的信息 0~k-1 节点,计算最佳总和并记录;然后后面节点 k+1,可以在 k-1,k-2 之间选择最佳方案。有点 Adaptive 的感觉。如代码二。

代码:

//code I
/* Time Limit Exceeded Solution*/
class Solution {
public:int rob(vector<int>& nums) {return rob_recursive(nums, 0);}//recusively cope with the subarrayint rob_recursive(vector<int>& nums, unsigned head){if (nums.size() > head) {int local_sum_1 = nums[head] + rob_recursive(nums, head + 2);  //skip the head+1if (nums.size() > head + 1){int local_sum_2 = nums[head + 1] + rob_recursive(nums, head + 3); //skip the head+2if (local_sum_1 < local_sum_2)return local_sum_2;}return local_sum_1;}return 0;}
};
//code II
class Solution {
public:int rob(vector<int>& nums) {vector<int> sum_record;unsigned length = nums.size();if (length == 0) return 0;if (length == 1) return *nums.begin();if (length == 2) return nums[0] > nums[1] ? nums[0] : nums[1];if (length == 3){return nums[0]+nums[2] > nums[1] ? nums[0] + nums[2] : nums[1];}sum_record.push_back(nums[0]);sum_record.push_back(nums[1]);sum_record.push_back(nums[0]+nums[2]);for (int i = 3; i < length;i++){   int pre = nums[i] + sum_record[i - 2];      //skip the i-1int pre_pre = nums[i] + sum_record[i - 3];  //skip the i-2sum_record.push_back(pre > pre_pre ? pre : pre_pre);}return sum_record[length - 1] > sum_record[length - 2] ? sum_record[length - 1] : sum_record[length - 2];}
};