-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhouse_robber.cpp
78 lines (72 loc) · 1.67 KB
/
house_robber.cpp
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
* =====================================================================================
*
* Filename: house_robber.cpp
*
* Description: 198. House Robber.
*
* Version: 1.0
* Created: 03/28/19 11:46:30
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), [email protected]
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <vector>
// Recursive
class Solution1
{
public:
int rob(const std::vector<int>& nums)
{
std::vector<int> amounts(nums.size(), -1);
return rob(nums, nums.size() - 1, &amounts);
}
private:
int rob(const std::vector<int>& nums, int idx, std::vector<int>* amounts)
{
if (idx < 0)
{
return 0;
}
else if (amounts->at(idx) != -1)
{
return amounts->at(idx);
}
int prev = rob(nums, idx - 1, amounts);
int curr = nums[idx] + rob(nums, idx - 2, amounts);
amounts->at(idx) = (prev > curr ? prev : curr);
return amounts->at(idx);
}
};
// Iterative
class Solution2
{
public:
int rob(const std::vector<int>& nums)
{
int adj = 0;
int pre = 0;
int cur = 0;
for (const auto val: nums)
{
cur = std::max(val + pre, adj);
pre = adj;
adj = cur;
}
return cur;
}
};
using Solution = Solution2;
int main(int argc, char* argv[])
{
std::vector<int> nums = {2, 7, 9, 3, 1};
auto money = Solution().rob(nums);
printf("Rob money: %d\n", money);
return 0;
}