LeetCode213:House Robber II,leetcode213robber
Note: This is an extension of House Robber.
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
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.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
續接前面的House Robber I 但是想了好久都沒想出來怎麼解。加上條件的DP問題需要進行一定的轉化才能成為標準的DP問題,這個轉化就成了關鍵。
這裡的關鍵就是最後那一個房間N和第一個房間相連了,可以這麼進行轉化:
考慮搶劫了第0個房間,那麼問題就是求搶劫第0~N-1個房間的最大數。
考慮不搶劫第0個房間,那麼問題就是求搶劫第1~N個房間的最大數。
上面轉化後的兩個問題就是House Robber I中的問題。再求上面兩個解的最大值,就是本題的解。
在做這題時發現House Robber I中的代碼還可以進一步的最佳化,可以將數組也省略掉而只使用兩個變數來儲存值,這樣空間複雜度也降到了O(1)。代碼更優了。
這是因為House Robber I只需要比較第A[i-2]+nums[i]和A[i-1]的大小,所以可以把House Robber I中的數組也省略掉,而只需要兩個變數來儲存著兩個值,這樣更能節約空間。這裡pLast儲存的是House Robber I中A[i-1]的值,ppLast儲存的是House Robber I中A[i-2]的值,邏輯和House Robber I是一樣的。
runtime:0ms
class Solution {public: int rob(vector<int>& nums) { int length=nums.size(); if(length==0) return 0; if(length==1) return nums[0]; return max(robDiv(nums,0,length-2),robDiv(nums,1,length-1)); } int robDiv(vector<int> &nums,int first,int last) { //因為只需要比較第A[i-2]+nums[i]和A[i-1]的大小,所以可以把House Robber I中的數組也省略掉, //而只需要兩個變數來儲存著兩個值,這樣更能節約空間。 //這裡pLast儲存的是House Robber I中A[i-1]的值, //ppLast儲存的是House Robber I中A[i-2]的值,邏輯和House Robber I是一樣的。 int pLast=0,ppLast=0; for(int i=first;i<=last;i++) { int tmp=pLast; pLast=max(ppLast+nums[i],pLast); ppLast=tmp; } return pLast; }};