题目:
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 andit 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 tonightwithout alerting the police.
题解:
这题的设定也是醉了。简单的动态规划。
C++版:
class Solution {
public:
int rob(vector<int>& nums) {
int globalMax = 0;
vector<int> robber(nums.size(), 0);
for(int i = 0; i < nums.size(); i++) {
robber[i] = nums[i];
int localMax = robber[i];
for(int j = i - 2; j >= 0; j--) {
if(robber[i] + robber[j] > localMax)
localMax = robber[i] + robber[j];
}
robber[i] = localMax;
if(localMax > globalMax)
globalMax = localMax;
}
return globalMax;
}
};Java版:
public class Solution {
public int rob(int[] nums) {
int global = 0;
int[] robber = new int[nums.length];
for(int i = 0; i < nums.length; i++) {
int local = nums[i];
robber[i] = nums[i];
for(int j = i - 2; j >= 0; j--) {
if(robber[i] + robber[j] > local)
local = robber[i] + robber[j];
}
robber[i] = local;
if(local > global)
global = local;
}
return global;
}
}Python版:
class Solution:
# @param {integer[]} nums
# @return {integer}
def rob(self, nums):
robber = [0] * len(nums)
rob = 0
for i in range(len(nums)):
robber[i] = nums[i]
local = nums[i]
for j in range(0, i - 1):
local = local if robber[i] + robber[j] <= local else robber[i] + robber[j]
robber[i] = local
if local > rob:
rob = local
return rob
本文介绍了一种使用动态规划解决相邻房屋安全系统连接问题的算法,以确定在不触发警报的情况下能抢劫的最大金额。通过C++、Java和Python三种语言实现,该算法展示了如何在复杂限制下优化决策过程。
: House Robber&spm=1001.2101.3001.5002&articleId=46657419&d=1&t=3&u=90d8105345504100a9b0a2dab5bde619)
539

被折叠的 条评论
为什么被折叠?



