House Robber(leetcode)

来源:互联网 发布:linux执行sh文件命令 编辑:程序博客网 时间:2024/06/02 02:07

原题如下:

You are aprofessional robber planning to rob houses along a street. Each house has acertain amount of money stashed, the only constraint stopping you from robbingeach of them is that adjacent houses have security system connected and it willautomatically contact the police if two adjacent houses were broken into on thesame night.

Given a list ofnon-negative integers representing the amount of money of each house, determinethe maximum amount of money you can rob tonight without alerting the police.

解题思路:这道题目乍一看还是挺麻烦的,说到底,就是找出一个数组中前n项中所有不相邻项数的和的最大值,这个如果用普通的方法还是挺麻烦的。这里我们考虑使用动态规划,假如我们想要求数组numn项中所有不相邻项的和的最大值(其中必须有num(n))max(n),要么max(n)=max(n-2)+num(n),要么max(n)=max(n-3)+num(n),当然,n=1,2,3的情况要单独拿出来考虑,最后将数组中所有项对应的max值都算出来,然后就是比较max(n-1)max(n)的大小了,返回较大的那一个即可。

算法:

1、       定义一个临时数组max(n,0)n为数组num的大小,max(i)代表前i项中包括num(i)的不相邻的项的和的最大值;

2、       先处理单个情况,当i=0,1,2时,单独求出max(i)

3、       i>=3时,max(i)max(i-2)+num(i)max(i-3)+num(i)中较大的那一个。

4、       最后结果:当n=1,时,返回max(n-1)即可;否则,返回max(n-1)max(n-2)中较大的那一个。

算法复杂度分析:整个函数只用了一层循环用来求各项的max,所以算法复杂度为O(n)

具体代码如下:

class Solution {

public:

   int rob(vector<int>& nums) {

       int n=nums.size();

       if(n==0)return 0;

       vector<int> max(n,0);

       for(int i=0;i<n;++i){

            if(i==0||i==1)max[i]=nums[i];

            elseif(i==2)max[i]+=max[i-2]+nums[i];

            else{

                   if(max[i-2]>max[i-3])

                   max[i]+=nums[i]+max[i-2];

                   else

                   max[i]+=nums[i]+max[i-3];

            }

       }

       if(n==1)return max[n-1];

       if(max[n-1]>max[n-2])returnmax[n-1];

       return max[n-2];

   }

};

0 0