https://leetcode.com/problems/house-robber/
The topic designed a robber's scene, in fact, is to find the array of nonadjacent data combined to get the maximum value
Give an example
Hypothetical data: 8 3 6 15 4 9 7 10
Then the first possible choice is 8, 3
Each number is selected according to his first two numbers, the first three numbers to get the maximum value to choose, until 6 when considering the front can only and 8 combination 8,3,14
To the number 15, you can consider combining 8,3,14,23,4,9,7,10 in 8,3
The next steps:
8,3,14,23,18,9,7,10
8,3,14,23,18,32,7,10
8,3,14,23,18,32,30,10
8,3,14,23,18,32,30,42, last 42.
Class Solution {public: int Rob (vector<int> &num) { if (Num.empty ()) { return 0; } int res = 0; int length = Num.size (); if (1 = = length) { return num[0]; } if (length >= 3) { num[2] = num[0]+num[2]; } for (int i = 3; i < length; i++) { if (num[i-2]>num[i-3]) { Num[i] + = Num[i-2]; } else { Num[i] + = num[i-3]; } } Return (Num[length-2]>num[length-1])? NUM[LENGTH-2]:NUM[LENGTH-1]; };
In fact this is a DP problem:
A[i][0] indicates that the first time no robbery, A[i][1] said I was robbed
i.e. a[i+1][0] = max (a[i][0], a[i][1]) ... So Rob's current house can only be equal to the last time no Rob's +money[i+1], then a[i+1][1] = a[i][0]+money[i+1].
In fact, only two variables are required to save the results, and no two-dimensional arrays are required.
[CPP]View Plaincopyprint?
- class solution {
- public :&NBSP;&NBSP;
- int rob (vector< int > &num) {
- int best0 = 0; // indicates that the current houses &NBSP;&NBSP;
- int best1 = 0; // indicates that the current houses &NBSP;&NBSP;
- for int i = 0; i < num.size (); i++) {
- int temp = best0;
- best0 = max (best0, best1); // does not select the current houses, it is equal to the last selected or not selected maximum value &NBSP;&NBSP;
- best1 = temp + num[i]; // selected the current houses, the value can only be equal to the last not selected + The current houses of money &NBSP;&NBSP;
- &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;
- return max (BEST0,&NBSP;BEST1);
- }
- };
Leetcode-house robber finding array nonadjacent maximum DP