House Robber && House RobberⅡ
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.
題目的意思:一個盜賊從一連串的房子裡(可以看成數組)偷東西,不能偷相鄰的房子(相鄰的房子被偷會觸發警報),最大能偷多少。轉換:從給定的一個數組中,取數相加,相鄰的不能取,能取的最大和是多少
思路,定義一個數組dp,dp[i]表示從1到i個數的能偷的最大值,對於i+1,我們知道,前i+1個房子(從1開始)最大值為前i個房子dp值和偷第i+1個房子加上dp[i-1](需要繞開i個房子)兩者的最大值,dp[i+1]=Max(dp[i],dp[i-1+nums[i]]),dp[0]=0,dp[1]=nums[1],
class Solution {public: int rob(vector<int>& nums) { if(nums.empty()) return 0; int len=nums.size(); if(len==1) return nums[0]; vector<int> dp(len+1,0); dp[1]=nums[0]; for(int i=2;i<=len;i++) { dp[i]=Max(dp[i-1],nums[i-1]+dp[i-2]); } return dp[len]; } int Max(int a,int b) { return a>b?a:b; }};
House RobbereⅡ
現在房子的主人聰明了,把所有房子連成一個圈,即第一個房子和最後一個房子也是相鄰的,問盜賊能偷的最大值是多少
思路:既然最後一個和第一個房子不能同時偷,那麼先去掉最後一個房子,求 1 到 len-1的最大值,然後去掉第一個房子,求2到len個房子的最大值,去兩者中 的 最大值
代碼如下
class Solution {public: int rob(vector<int>& nums) { if(nums.empty()) return 0; int len=nums.size(); if(len==1) return nums[0]; return Max(rob(nums,0,len-1),rob(nums,1,len)); } int rob(vector<int> &nums,int start,int end) { vector<int> dp(end+1,0); dp[start+1]=nums[start]; dp[start]=0; for(int i=start+2;i<=end;i++) { dp[i]=Max(dp[i-1],dp[i-2]+nums[i-1]); } return dp[end]; } int Max(int a,int b) { return a>b?a:b; }};