House robber
You is a professional robber planning to rob houses along a street. Each house have a certain amount of money stashed, the only constraint stopping all from robbing each of the them are that Adjac ENT houses have security system connected and it would automatically contact the police if the adjacent houses were broken Into on the same night.
Given a list of non-negative integers representing the amount of money in each house, determine the maximum amount of mone Y you can rob tonight without alerting the police.
Ideas:
Dynamic planning, Dp[i] represents the maximum benefit to the house I, there are two cases, or the House can not be robbed, because the previous one has been visited, and the other is that the house can be robbed, so the maximum benefit of the two before the return of the building. In mathematical expression: dp[i] = max (num[i]+dp[i-2], dp[i-1]
Exercises
classSolution { Public: intRob (vector<int> &num) { intn=num.size (); if(n==0) return 0; if(n==1) returnnum[0]; if(n==1) returnMax (num[0], num[1]); int*DP =New int[n]; dp[0] = num[0]; dp[1] = max (num[0], num[1]); for(intI=2; i<n;i++) {Dp[i]= Max (num[i]+dp[i-2], dp[i-1]); } returndp[n-1]; }};
View Code
Something:
The above method space complexity of 0 (n), in fact, can also be optimized to O (1), which is similar to the topic of another DP climbing stairs
classSolution { Public: intRob (vector<int> &num) { intn=num.size (); if(n==0) return 0; if(n==1) returnnum[0]; if(n==2) returnMax (num[0], num[1]); intPre2 = num[0]; intPre1 = Max (num[0], num[1]); intcur; for(intI=2; i<n;i++) {cur= Max (pre2+Num[i], pre1); Pre2=Pre1; Pre1=cur; } returncur; }};
View Code
[Leetcode] House robber