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: problems/1049-last-stone-weight-ii.md
+14-19
Original file line number
Diff line number
Diff line change
@@ -75,7 +75,7 @@ These five steps are a pattern for solving `Dynamic Programming` problems.
75
75
```
76
76
* You can see the `dp` array size is one greater than the knapsack size. In this way, the backpack size and index value are equal, which helps to understand.
77
77
*`dp[0]` is set to `true`, indicating that an empty backpack can be achieved by not putting any items in it. In addition, it is used as the starting value, and the subsequent `dp[j]` will depend on it. If it is `false`, all values of `dp[j]` will be `false`.
78
-
*`dp[j] = false (j != 0)`, indicating that it is impossible to get `j` with no `nums`.
78
+
*`dp[j] = false (j != 0)`, indicating that it is impossible to get `j` with no `stones`.
79
79
80
80
3. Determine the `dp` array's recurrence formula
81
81
* Try to complete the grid. In the process, you will get inspiration to derive the formula.
@@ -127,7 +127,7 @@ class Solution:
127
127
128
128
for stone in stones:
129
129
# If traversing from left to right, the newly assigned value `dp[j]` will act as `dp[j - stone]` later,
130
-
# then the subsequent `dp[j]` will be affected. But each `stone` can only be used once.
130
+
# then the subsequent `dp[j]` will be affected. But each `stone` can only be used once!
131
131
for j inrange(len(dp) -1, 0, -1):
132
132
if j < stone:
133
133
break
@@ -136,8 +136,6 @@ class Solution:
136
136
for i inrange(len(dp) -1, -1, -1):
137
137
if dp[i]:
138
138
return sum_ - i *2
139
-
140
-
raiseArithmeticError("lastStoneWeightII() doesn't have a correct return value!")
141
139
```
142
140
143
141
## C++
@@ -222,24 +220,22 @@ public class Solution {
222
220
## JavaScript
223
221
```javascript
224
222
varlastStoneWeightII=function(stones) {
225
-
constsum=_.sum(stones)
223
+
constsum=_.sum(stones)
226
224
227
-
constdp=Array(Math.floor(sum /2) +1).fill(false)
228
-
dp[0] =true
225
+
constdp=Array(Math.floor(sum /2) +1).fill(false)
226
+
dp[0] =true
229
227
230
-
for (conststoneof stones) {
231
-
for (let j =dp.length-1; j >= stone; j--) {
232
-
dp[j] = dp[j] || dp[j - stone]
233
-
}
228
+
for (conststoneof stones) {
229
+
for (let j =dp.length-1; j >= stone; j--) {
230
+
dp[j] = dp[j] || dp[j - stone]
234
231
}
232
+
}
235
233
236
-
for (let j =dp.length-1; j >=0; j--) {
237
-
if (dp[j]) {
238
-
return sum - j *2
239
-
}
234
+
for (let j =dp.length-1; j >=0; j--) {
235
+
if (dp[j]) {
236
+
return sum - j *2
240
237
}
241
-
242
-
return-1; // This line should be unreachable. It represents an error state.
0 commit comments