leetcode:198 House Robber-每日编程第二十二题

来源:互联网 发布:百度统计 数据 编辑:程序博客网 时间:2024/06/10 18:55

House Robber

Total Accepted: 44999Total Submissions: 140629 Difficulty: Easy

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.


思路:arr[i]表示以第i个被偷为前提,前i+1个屋子最多可以偷多少钱。

arr[i]=max(arr[i-2],arr[i-3])+num[i];

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


0 0
原创粉丝点击