[LeetCode]--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.

分析

       根据题意,要在不能抢劫相邻住所的前提下,得到最大抢劫财富。这是一道比较典型的动态规划问题。设rob(i)为到第i幢房子所能得到的最大财富,w(i)为第i幢房子所具有的钱财,则显然rob(i)=max{rob(i-2)+w(i), rob(i-1)},即每到一幢房子,我们需要确定是抢劫前一幢的钱财,还是抢劫隔一幢和当前幢的钱财,这样计算到rob(n),就是所有n幢房子可以抢劫到的最多钱财。
       需要注意的是,如果没有房子可供抢劫,自然结果为0;如果只有一幢房子,那么这幢房子所具有的钱财即是最终结果;而对于到达第二幢房子所能抢到最多钱财,我们需要决定是抢劫第一幢还是第二幢,也即rob(1)=max{w(0), w(1)},这里下标从0开始。

解答

class Solution {
public:
    int rob(vector<int>& nums) {
        int length=nums.size();
    	if(length==0){
    		return 0;
		}
        int* rob=new int[length];
        rob[0]=nums[0];
        if(nums[0]>nums[1]){
        	rob[1]=nums[0];
		}
        else{
        	rob[1]=nums[1];
		}
        if(length==1)
        	return rob[0];
        else if(length==2)
        	return rob[1];
		else{
			for(int i=2;i<length;i++){
        		if(rob[i-2]+nums[i]>rob[i-1]){
        			rob[i]=rob[i-2]+nums[i];
				}
				else rob[i]=rob[i-1];
			}
			return rob[length-1];
		}
    }
};

      时间复杂度为O(n).

猜你喜欢

转载自blog.csdn.net/weixin_38057349/article/details/78958928