LeetCode 198. House Robber

来源:互联网 发布:linux进入命令模式 编辑:程序博客网 时间:2024/04/29 05:29

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.

简单DP,状态转移方程:d(i)=max{d(i-2) + nums[i], d(i-1)}

class Solution {public:    int rob(vector<int>& nums) {        int i;        vector<int> d;        int len = nums.size();        if(len == 0) return 0;        else if(len == 1) return nums[0];        else if(len == 2) return nums[0] > nums[1]?nums[0] : nums[1];        d.push_back(nums[0]);        d.push_back(nums[0] > nums[1]?nums[0] : nums[1]);        for(i = 2; i < len; i ++){            d.push_back(max(d[i - 2] + nums[i], d[i - 1]));        }        return d[len - 1];    }};


0 0
原创粉丝点击