File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * lc416 (https://leetcode.com/problems/partition-equal-subset-sum/)
3
+ * Given a non-empty array containing only positive integers,
4
+ * find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
5
+ * @param {number[] } nums
6
+ * @return {boolean }
7
+ */
8
+ var canPartition = function ( nums ) {
9
+ const sum = nums . reduce ( ( acc , num ) => acc + num , 0 ) ;
10
+ if ( sum % 2 === 1 ) {
11
+ return false ;
12
+ }
13
+
14
+ const half = sum / 2 ;
15
+
16
+ const dp = [ ] ;
17
+ for ( let i = 0 ; i <= nums . length ; i ++ ) {
18
+ dp [ i ] = [ ] ;
19
+ dp [ i ] [ 0 ] = true ;
20
+ }
21
+
22
+ for ( let j = 0 ; j <= half ; j ++ ) {
23
+ dp [ 0 ] [ j ] = false ;
24
+ }
25
+ dp [ 0 ] [ 0 ] = true ;
26
+
27
+ for ( let i = 1 ; i <= nums . length ; i ++ ) {
28
+ for ( let j = 1 ; j <= half ; j ++ ) {
29
+ dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ;
30
+ if ( nums [ i - 1 ] <= j ) {
31
+ dp [ i ] [ j ] = ( dp [ i - 1 ] [ j - nums [ i - 1 ] ] || dp [ i ] [ j ] ) ;
32
+ }
33
+ }
34
+ }
35
+
36
+ return dp [ nums . length ] [ half ] ;
37
+ } ;
You can’t perform that action at this time.
0 commit comments