LeetCode213:House Robber II,leetcode213robber

來源:互聯網
上載者:User

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;    }};



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.