Leetcode14: House Robber

来源:互联网 发布:cf手游外卦软件 编辑:程序博客网 时间:2024/06/05 03:08

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];            }};



1 1