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

House Robber -- leetcode

时间:2015-07-06 18:11:40      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:leetcode   动态规划   

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.




基本思路:动态规划

设cash[i]  是抢劫第i所(含)以前所有房子得到的现金。

则cash[i+1] = max( nums[i+1] + cash[i-1], cash[i])

即,如果再加入一所房子,所能是到最大现金的方式为两种:  

1, 是抢劫当前房子,并加上,抢动前面房子所得到的最大现金(不包含前面紧临的房子)

2, 不抢劫当前房子,实际得到的现金,为抢动前面房子所得的最大现金(包含前面坚临的房子)                                         

取两者途径较大者,为抢劫当前房子(含)之前所得到的最多大现金。


实际运算中,不需要一维数组。只需要两个变量就成。分别保存上一次,和上上一次计算结果。


class Solution {
public:
    int rob(vector<int>& nums) {
        int last = 0;
        int last_last = 0;
        for (auto i: nums) {
            int current = max(i+last_last, last);
            last_last = last;
            last = current;
        }
        return last;
    }
};


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

House Robber -- leetcode

标签:leetcode   动态规划   

原文地址:http://blog.csdn.net/elton_xiao/article/details/46775115

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