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.
用分治来做。时间复杂度O(n^2),貌似是最优了。
class Solution {
public:
int divide(vector<int> &num,int p,int r){
if(p>r) return 0;
else if(p >= r-1) return max(num[p],num[r]); //p==r or p==r-1
int m = (p+r)/2;
return max(divide(num,p,m)+divide(num,m+2,r) , divide(num,p,m-1)+divide(num,m+1,r));
}
int rob(vector<int> &num) {
if(num.size()==0) return 0;
return divide(num,0,num.size()-1);
}
};