题目:入室盗贼
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.
题意:
你是一名专业强盗,计划沿着一条街打家劫舍。每间房屋都储存有一定数量的金钱,唯一能阻止你打劫的约束条件就是:由于房屋之间有安全系统相连,如果同一个晚上有两间相邻的房屋被闯入,它们就会自动联络警察,因此不可以打劫相邻的房屋。
给定一列非负整数,代表每间房屋的金钱数,计算出在不惊动警察的前提下一晚上最多可以打劫到的金钱数。
思路一:
使用动态规划的思想实现,主要考虑的是当前房屋偷或者不偷对总的收入是否有增加。如果决定偷,则上一步必须是不偷,那么这一步的利润为num[i]+noTake的值,如果决定不偷,则上一步的状态就无所谓是不是偷过,所以直接将上一步的总收入赋值给这一步结果就行。综合可得,到达本房屋时最大利润为max(偷的收入,不偷的收入)取最大值即可。
代码:java版:0ms
public class Solution { public int rob(int[] nums) { int take = 0, maxProfit = 0, noTake = 0; for (int i=0; i<nums.length; ++i) { take = noTake + nums[i]; noTake = maxProfit; maxProfit = Math.max(take, noTake); } return maxProfit; } }
代码:C++版:0ms
class Solution { public: int rob(vector<int>& nums) { if (nums.size() <=1) return nums.empty() ? 0 : nums[0]; vector<int> dp = {nums[0], max(nums[0], nums[1])}; for (int i=2; i<nums.size(); ++i) { dp.push_back(max(nums[i] + dp[i-2], dp[i-1])); } return dp.back(); } };另一种写法:代码:C++版:0ms
class Solution { public: int rob(vector<int>& nums) { int take = 0, noTake = 0; for (int i=0; i<nums.size(); ++i) { int temp = take; take = noTake + nums[i]; noTake = max(temp, noTake); } return max(take, noTake); } };
思路二:
按照奇偶来取房屋,这样可以保证安全,每一步的过程中对当前奇偶最大值进行比较,以确定当前房屋是否偷。
代码:C++版:0ms
class Solution { public: int rob(vector<int>& nums) { int even = 0, odd = 0; for (int i=0; i<nums.size(); ++i) { if (i%2 == 0) { even += nums[i]; even = max(even, odd); } else { odd += nums[i]; odd = max(even, odd); } } return max(even, odd); } };