forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain4.cpp
More file actions
50 lines (36 loc) · 1.02 KB
/
main4.cpp
File metadata and controls
50 lines (36 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/// Source : https://leetcode.com/problems/house-robber/description/
/// Author : liuyubobobo
/// Time : 2017-11-19
#include <iostream>
#include <vector>
using namespace std;
/// Memory Search
/// Another way to define the states
/// Time Complexity: O(n)
/// Space Complexity: O(n)
class Solution {
private:
// the max profit for robbing nums[0...i]
vector<int> memo;
int tryRob(const vector<int> &nums, int index){
if(index < 0)
return 0;
if(memo[index] != -1)
return memo[index];
return memo[index] = max(tryRob(nums, index - 1),
nums[index] + tryRob(nums, index - 2));
}
public:
int rob(vector<int>& nums) {
memo.clear();
for(int i = 0 ; i < nums.size() ; i ++)
memo.push_back(-1);
return tryRob(nums, nums.size() - 1 );
}
};
int main() {
int nums[] = {2, 1};
vector<int> vec(nums, nums + sizeof(nums)/sizeof(int));
cout << Solution().rob(vec) << endl;
return 0;
}