[LeetCode] 198. House Robber, leetcode198.house
Question
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.
Ideas
The essence of this question is to extract one or more non-adjacent numbers from an array to maximize the sum.
This is a dynamic planning problem.
We maintain an array of dp, where dp [I] indicates the maximum sum formed by non-adjacent numbers at the I position.
State transition equation:
Dp [0] = num [0] (when I = 0) dp [1] = max (num [0], num [1]) (when I = 1) dp [I] = max (num [I] + dp [I-2], dp [I-1]) (when I! = 0 and I! = 1 hour)
Code
/* ------------------------------------------------------------------- * Date: 2014-04-08 * Author: SJF0115 * Subject: 198. house Robber * Source: https://leetcode.com/problems/house-robber/* result: AC * Source: LeetCode * Summary: Author */# include <iostream> # include <vector> using namespace std; class Solution {public: int rob (vector <int> & num) {if (num. empty () {return 0;} // if int size = num. size (); vector <int> dp (size, 0); // dp [I] = max (num [I] + dp [I-2], dp [I-1]) // dp [I] indicates [0, I] taking the maximum benefit of one or more non-adjacent values dp [0] = num [0]; dp [1] = max (num [0], num [1]); for (int I = 2; I <size; ++ I) {dp [I] = max (dp [I-1], dp [I-2] + num [I]);} // for return dp [size-1] ;}}; int main () {Solution solution; vector <int> num = {4, 3, 3, 2}; cout <solution. rob (num) <endl; return 0 ;}
Running time
Space Optimization
Replace the dp array with its own array.
/* ------------------------------------------------------------------- * Date: 2014-04-08 * Author: SJF0115 * Subject: 198. house Robber * Source: https://leetcode.com/problems/house-robber/ * result: AC * Source: LeetCode * Summary: Memory */# include <iostream> # include <vector> using namespace std; class Solution {public: int rob (vector <int> & num) {if (num. empty () {return 0;} // if int size = num. size (); num [1] = max (num [0], num [1]); for (int I = 2; I <size; ++ I) {num [I] = max (num [I-1], num [I-2] + num [I]);} // for return num [size-1] ;}}; int main () {Solution solution; vector <int> num = {4, 3, 3, 2}; cout <solution. rob (num) <endl; return 0 ;}
Running time