Skip to content

Commit a439fed

Browse files
authored
Update Solution.cpp
1 parent f847f10 commit a439fed

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

solution/0100-0199/0198.House Robber/Solution.cpp

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,17 @@ class Solution {
22
public:
33
int rob(vector<int>& nums) {
44
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];
5+
int f[n];
6+
memset(f, -1, sizeof(f));
7+
auto dfs = [&](auto&& dfs, int i) -> int {
8+
if (i >= n) {
9+
return 0;
10+
}
11+
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);
1217
}
13-
};
18+
};

0 commit comments

Comments
 (0)