You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@@ -54,7 +54,174 @@ Total amount you can rob = 2 + 9 + 1 = 12.
54
54
55
55
<!-- solution:start -->
56
56
57
-
### Solution 1: Dynamic Programming
57
+
### Solution 1: Memoization Search
58
+
59
+
We design a function $\textit{dfs}(i)$, which represents the maximum amount of money that can be stolen starting from the $i$-th house. Thus, the answer is $\textit{dfs}(0)$.
60
+
61
+
The execution process of the function $\textit{dfs}(i)$ is as follows:
62
+
63
+
- If $i \ge \textit{len}(\textit{nums})$, it means all houses have been considered, and we directly return $0$;
64
+
- Otherwise, consider stealing from the $i$-th house, then $\textit{dfs}(i) = \textit{nums}[i] + \textit{dfs}(i+2)$; if not stealing from the $i$-th house, then $\textit{dfs}(i) = \textit{dfs}(i+1)$.
To avoid repeated calculations, we use memoization search. The result of $\textit{dfs}(i)$ is saved in an array or hash table. Before each calculation, we first check if it has been calculated. If so, we directly return the result.
68
+
69
+
The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ is the length of the array.
70
+
71
+
<!-- tabs:start -->
72
+
73
+
#### Python3
74
+
75
+
```python
76
+
classSolution:
77
+
defrob(self, nums: List[int]) -> int:
78
+
@cache
79
+
defdfs(i: int) -> int:
80
+
if i >=len(nums):
81
+
return0
82
+
returnmax(nums[i] + dfs(i +2), dfs(i +1))
83
+
84
+
return dfs(0)
85
+
```
86
+
87
+
#### Java
88
+
89
+
```java
90
+
classSolution {
91
+
privateInteger[] f;
92
+
privateint[] nums;
93
+
94
+
publicintrob(int[] nums) {
95
+
this.nums = nums;
96
+
f =newInteger[nums.length];
97
+
return dfs(0);
98
+
}
99
+
100
+
privateintdfs(inti) {
101
+
if (i >= nums.length) {
102
+
return0;
103
+
}
104
+
if (f[i] ==null) {
105
+
f[i] =Math.max(nums[i] + dfs(i +2), dfs(i +1));
106
+
}
107
+
return f[i];
108
+
}
109
+
}
110
+
```
111
+
112
+
#### C++
113
+
114
+
```cpp
115
+
classSolution {
116
+
public:
117
+
int rob(vector<int>& nums) {
118
+
int n = nums.size();
119
+
int f[n];
120
+
memset(f, -1, sizeof(f));
121
+
auto dfs = [&](auto&& dfs, int i) -> int {
122
+
if (i >= n) {
123
+
return 0;
124
+
}
125
+
if (f[i] < 0) {
126
+
f[i] = max(nums[i] + dfs(dfs, i + 2), dfs(dfs, i + 1));
We notice that when $i \gt 2$, $f[i]$ is only related to $f[i-1]$ and $f[i-2]$. Therefore, we can use two variables instead of an array to reduce the space complexity to $O(1)$.
195
364
@@ -263,81 +432,29 @@ function rob(nums: number[]): number {
0 commit comments