Leetcode 198. House Robber

来源:互联网 发布:淘宝图片侵权赔偿标准 编辑:程序博客网 时间:2024/05/23 13:25

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.

//错误

</pre><pre name="code" class="cpp">        int sum=0;        if(nums.size()==1)return nums[nums.size()-1];        if(nums.size()==2){            sort(nums.begin(),nums.end());            return nums[nums.size()-1];        }        vector<int> nums2=nums;        sort(nums2.begin(),nums2.end());        int l=1000;        for(int j=nums2.size()-1;j>=(nums2.size()-(nums2.size()/2+1));j--){            int flag=0;            for(int i=0;i<nums.size();i++){                    while((nums[i]==nums2[j])&&(l!=i)&&(l!=i+1)&&(l!=i-1)){                         sum=sum+nums[i];                         l=i;                         flag=1;                     }                     if(flag)break;            }            }            return sum;        }};

//正确答案

class Solution {public:    int rob(vector<int>& nums) {//DP思想              int n=nums.size();       if(n==0) return 0;       if(n==1) return nums[0];      vector<int> m(n,0);<strong><span style="color:#006600;">//必须初始化,否则超出运行时间      //不对vector进行初始化,则为空,不能调用nums[i]----猜测可能的原因</span></strong>
     //vector对象的下标运算可以用于访问已经存在的元素,
     <span style="font-family: Arial, Helvetica, sans-serif;"> //不能用来添加元素,添加元素push_back()或者初始化</span></strong></span>
       m[0]=nums[0];       m[1]=max(nums[0],nums[1]);       for(int i=2;i<n;i++){           m[i]=max(m[i-1],m[i-2]+nums[i]);       }      return m[n-1];        }};



0 0