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
Copy file name to clipboardexpand all lines: solution/1500-1599/1553.Minimum Number of Days to Eat N Oranges/README_EN.md
+42-4
Original file line number
Diff line number
Diff line change
@@ -53,15 +53,32 @@ You need at least 3 days to eat the 6 oranges.
53
53
54
54
## Solutions
55
55
56
-
### Solution 1
56
+
### Solution 1: Memoization Search
57
+
58
+
According to the problem description, for each $n$, we can choose one of three ways:
59
+
60
+
1. Decrease $n$ by $1$;
61
+
2. If $n$ can be divided by $2$, divide the value of $n$ by $2$;
62
+
3. If $n$ can be divided by $3$, divide the value of $n$ by $3$.
63
+
64
+
Therefore, the problem is equivalent to finding the minimum number of days to reduce $n$ to $0$ through the above three ways.
65
+
66
+
We design a function $dfs(n)$, which represents the minimum number of days to reduce $n$ to $0$. The execution process of the function $dfs(n)$ is as follows:
67
+
68
+
1. If $n < 2$, return $n$;
69
+
2. Otherwise, we can first reduce $n$ to a multiple of $2$ by $n \bmod 2$ operations of $1$, and then perform operation $2$ to reduce $n$ to $n/2$; we can also first reduce $n$ to a multiple of $3$ by $n \bmod 3$ operations of $1$, and then perform operation $3$ to reduce $n$ to $n/3$. We choose the minimum of the above two ways, that is, $1 + \min(n \bmod 2 + dfs(n/2), n \bmod 3 + dfs(n/3))$.
70
+
71
+
To avoid repeated calculations, we use the method of memoization search and store the calculated values of $dfs(n)$ in a hash table.
72
+
73
+
The time complexity is $O(\log^2 n)$, and the space complexity is $O(\log^2 n)$.
57
74
58
75
<!-- tabs:start -->
59
76
60
77
```python
61
78
classSolution:
62
79
defminDays(self, n: int) -> int:
63
80
@cache
64
-
defdfs(n):
81
+
defdfs(n: int) -> int:
65
82
if n <2:
66
83
return n
67
84
return1+min(n %2+ dfs(n //2), n %3+ dfs(n //3))
@@ -101,8 +118,12 @@ public:
101
118
}
102
119
103
120
intdfs(int n) {
104
-
if (n < 2) return n;
105
-
if (f.count(n)) return f[n];
121
+
if (n < 2) {
122
+
return n;
123
+
}
124
+
if (f.count(n)) {
125
+
return f[n];
126
+
}
106
127
int res = 1 + min(n % 2 + dfs(n / 2), n % 3 + dfs(n / 3));
0 commit comments