File tree 2 files changed +46
-0
lines changed
2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change 527
527
695|[ Max Area of Island] ( ./0695-max-area-of-island.js ) |Medium|
528
528
696|[ Count Binary Substrings] ( ./0696-count-binary-substrings.js ) |Easy|
529
529
697|[ Degree of an Array] ( ./0697-degree-of-an-array.js ) |Easy|
530
+ 698|[ Partition to K Equal Sum Subsets] ( ./0698-partition-to-k-equal-sum-subsets.js ) |Medium|
530
531
700|[ Search in a Binary Search Tree] ( ./0700-search-in-a-binary-search-tree.js ) |Easy|
531
532
701|[ Insert into a Binary Search Tree] ( ./0701-insert-into-a-binary-search-tree.js ) |Medium|
532
533
703|[ Kth Largest Element in a Stream] ( ./0703-kth-largest-element-in-a-stream.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 698. Partition to K Equal Sum Subsets
3
+ * https://leetcode.com/problems/partition-to-k-equal-sum-subsets/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given an integer array nums and an integer k, return true if it is possible to divide this
7
+ * array into k non-empty subsets whose sums are all equal.
8
+ */
9
+
10
+ /**
11
+ * @param {number[] } nums
12
+ * @param {number } k
13
+ * @return {boolean }
14
+ */
15
+ var canPartitionKSubsets = function ( nums , k ) {
16
+ const sum = nums . reduce ( ( a , b ) => a + b ) ;
17
+ if ( sum % k !== 0 ) {
18
+ return false ;
19
+ }
20
+
21
+ const target = sum / k ;
22
+ nums . sort ( ( a , b ) => b - a ) ;
23
+ if ( nums [ 0 ] > target ) {
24
+ return false ;
25
+ }
26
+
27
+ const used = new Array ( nums . length ) . fill ( false ) ;
28
+ return backtrack ( 0 , 0 , 0 ) ;
29
+
30
+ function backtrack ( index , count , updatedSum ) {
31
+ if ( count === k ) return true ;
32
+ if ( updatedSum === target ) return backtrack ( 0 , count + 1 , 0 ) ;
33
+ if ( updatedSum > target ) return false ;
34
+
35
+ for ( let i = index ; i < nums . length ; i ++ ) {
36
+ if ( ! used [ i ] ) {
37
+ used [ i ] = true ;
38
+ if ( backtrack ( i + 1 , count , updatedSum + nums [ i ] ) ) return true ;
39
+ used [ i ] = false ;
40
+ if ( updatedSum === 0 ) break ;
41
+ }
42
+ }
43
+ return false ;
44
+ }
45
+ } ;
You can’t perform that action at this time.
0 commit comments