标签:size run amp ++i ber 假设 ast one const
刚开始没有思路,看了一下别人的思路,假设只有第一件房子,没有最后一间,以及没有第一间,只有最后一间。分别考虑这两种情况的money,哪个大就选哪个,所以只要利用house rob I的那个函数即可
class Solution {
public:
int rob(vector<int>& nums) {
if (nums.size() <= 1) return nums.empty() ? 0 : nums[0];
return max(rob(nums, 0, nums.size() - 1), rob(nums, 1, nums.size()));
}
int rob(vector<int> &nums, int left, int right) {
if (right - left <= 1) return nums[left];
vector<int> dp(right, 0);
dp[left] = nums[left];
dp[left + 1] = max(nums[left], nums[left + 1]);
for (int i = left + 2; i < right; ++i) {
dp[i] = max(nums[i] + dp[i - 2], dp[i - 1]);
}
return dp.back();
}
};
Runtime:8ms,第二种方法和第一种思路相同。
class Solution { public: int rob(vector<int>& nums) { const int N = nums.size(); if (N == 0) return 0; if (N < 3) return *max_element(nums.begin(), nums.end()); vector<int> nums_first(nums.begin(), --nums.end()); vector<int> nums_last(++nums.begin(), nums.end()); return max(rob_one(nums_first), rob_one(nums_last)); } int rob_one(vector<int>& nums) { const int N = nums.size(); int preprev = 0; int prev = 0; for (int i = N - 1; i >= 0; --i) { const int x = nums[i]; const int tmp = max(x + preprev, prev); preprev = prev; prev = tmp; } return prev; } };
标签:size run amp ++i ber 假设 ast one const
原文地址:https://www.cnblogs.com/illfuckingkyzb/p/10226945.html