File tree 1 file changed +10
-22
lines changed
solution/0400-0499/0416.Partition Equal Subset Sum
1 file changed +10
-22
lines changed Original file line number Diff line number Diff line change @@ -193,36 +193,24 @@ function canPartition(nums: number[]): boolean {
193
193
194
194
``` rust
195
195
impl Solution {
196
- #[allow(dead_code)]
197
196
pub fn can_partition (nums : Vec <i32 >) -> bool {
198
- let mut sum = 0 ;
199
- for e in & nums {
200
- sum += * e ;
201
- }
202
-
203
- if sum % 2 != 0 {
197
+ let s : i32 = nums . iter (). sum ();
198
+ if s % 2 != 0 {
204
199
return false ;
205
200
}
206
-
201
+ let m = ( s / 2 ) as usize ;
207
202
let n = nums . len ();
208
- let m = (sum / 2 ) as usize ;
209
- let mut dp : Vec <Vec <bool >> = vec! [vec! [false ; m + 1 ]; n + 1 ];
210
-
211
- // Initialize the dp vector
212
- dp [0 ][0 ] = true ;
213
-
214
- // Begin the actual dp process
203
+ let mut f = vec! [vec! [false ; m + 1 ]; n + 1 ];
204
+ f [0 ][0 ] = true ;
205
+
215
206
for i in 1 ..= n {
207
+ let x = nums [i - 1 ] as usize ;
216
208
for j in 0 ..= m {
217
- dp [i ][j ] = if (nums [i - 1 ] as usize ) > j {
218
- dp [i - 1 ][j ]
219
- } else {
220
- dp [i - 1 ][j ] || dp [i - 1 ][j - (nums [i - 1 ] as usize )]
221
- };
209
+ f [i ][j ] = f [i - 1 ][j ] || (j >= x && f [i - 1 ][j - x ]);
222
210
}
223
211
}
224
-
225
- dp [n ][m ]
212
+
213
+ f [n ][m ]
226
214
}
227
215
}
228
216
```
You can’t perform that action at this time.
0 commit comments