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

Leetcode14: House Robber

时间:2015-04-21 16:17:04      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:leetcode   algorithm   

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的数组之前我已经得到的最大值,这个最大值要么取到了num[i]要么没取到num[i]。那么递推的表达式其实就是dp[i]=max(dp[i-1], dp[i-2]+num[i]);初始条件dp[0]=num[0],dp[1]=max(dp[0], num[1])。

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



Leetcode14: House Robber

标签:leetcode   algorithm   

原文地址:http://blog.csdn.net/u013089961/article/details/45170115

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