House Robber && House RobberⅡ__leetcode

來源:互聯網
上載者:User
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;    }};

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.