We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent f847f10 commit a439fedCopy full SHA for a439fed
solution/0100-0199/0198.House Robber/Solution.cpp
@@ -2,12 +2,17 @@ class Solution {
2
public:
3
int rob(vector<int>& nums) {
4
int n = nums.size();
5
- int f[n + 1];
6
- memset(f, 0, sizeof(f));
7
- f[1] = nums[0];
8
- for (int i = 2; i <= n; ++i) {
9
- f[i] = max(f[i - 1], f[i - 2] + nums[i - 1]);
10
- }
11
- return f[n];
+ int f[n];
+ memset(f, -1, sizeof(f));
+ auto dfs = [&](auto&& dfs, int i) -> int {
+ if (i >= n) {
+ return 0;
+ }
+ if (f[i] < 0) {
12
+ f[i] = max(nums[i] + dfs(dfs, i + 2), dfs(dfs, i + 1));
13
14
+ return f[i];
15
+ };
16
+ return dfs(dfs, 0);
17
}
-};
18
+};
0 commit comments