您的位置:首页 > 编程语言

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

2015-12-13 10:54 656 查看
House Robber

Total Accepted: 44999
Total 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]);
        
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: