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

[leetcode] House Robber

时间:2015-03-31 21:57:29      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

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.

思路:

动态规划,dp[i]代表到第i个房子的最大收益,这就有两种情况,或者这栋房子不能抢,因为前一栋已经光顾了;另一种就是这栋房子能抢,因此最大收益就为两栋之前的收益加上这栋的。用数学表达就是: dp[i] = max(num[i]+dp[i-2], dp[i-1]

题解:

技术分享
class Solution {
public:
    int rob(vector<int> &num) {
        int n=num.size();
        if(n==0)
            return 0;
        if(n==1)
            return num[0];
        if(n==1)
            return max(num[0], num[1]);
        int *dp = new int[n];
        dp[0] = num[0];
        dp[1] = max(num[0], num[1]);
        for(int i=2;i<n;i++) {
            dp[i] = max(num[i]+dp[i-2], dp[i-1]);
        }
        return dp[n-1];
    }
};
View Code

后话:

上面的方法空间复杂度为0(n),其实还可以优化成O(1)的,这很像另一道dp的题目climbing stairs

技术分享
class Solution {
public:
    int rob(vector<int> &num) {
        int n=num.size();
        if(n==0)
            return 0;
        if(n==1)
            return num[0];
        if(n==2)
            return max(num[0], num[1]);
        int pre2 = num[0];
        int pre1 = max(num[0], num[1]);
        int cur;
        for(int i=2;i<n;i++) {
            cur  = max(pre2+num[i], pre1);
            pre2 = pre1;
            pre1 = cur;
        }
        return cur;
    }
};
View Code

 

[leetcode] House Robber

标签:

原文地址:http://www.cnblogs.com/jiasaidongqi/p/4381906.html

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