[leetcode] 198. House Robber
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.
若抢了最后一家,则倒数第二家一定没抢,若没抢最后一家,则相当于只抢前几家。
因此可得:re[n] = max(money[n] + re[n-2], re[n-1])
用递归的话会超时,因此用循环,其实因为只跟n-1和n-2有关可以只存两个,因为都比较简单这里就不给出了。
我的代码:
class Solution { public: int rob(vector<int>& nums) { int len = nums.size(); if (len == 0) return 0; if (len == 1) return nums[0]; if (len == 2) return max(nums[0], nums[1]); vector<int> re; re.push_back(nums[0]); re.push_back(max(nums[0], nums[1])); for (int i = 2; i < len; i++) { re.push_back(max(re[i-1], nums[i] + re[i-2])); } return re[len-1]; } };