码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-198-House Robber

时间:2015-07-29 12:23:43      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:leetcode   dp   动态规划   

                                                   House Robber

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.

强盗进入房子盗窃,且不能进入两相邻的房间盗窃,求最大利益。

即在一个数组里选若干个数,选中的数不能相邻,求它们最大的和。



动态规划。

MAX[i]为到第i间房子的最大利润。

MAX[i] = max(MAX[i - 2] + nums[i] , MAX[i - 1])


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


版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode-198-House Robber

标签:leetcode   dp   动态规划   

原文地址:http://blog.csdn.net/u014705854/article/details/47123535

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!