标签:
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]; } };
后话:
上面的方法空间复杂度为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; } };
标签:
原文地址:http://www.cnblogs.com/jiasaidongqi/p/4381906.html