File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 1+ function check ( arr ) {
2+ let temp = arr [ 0 ] ;
3+ for ( let i = 1 ; i < arr . length ; i ++ ) {
4+ if ( arr [ i ] !== temp ) {
5+ return false ;
6+ }
7+ }
8+ return true ;
9+ }
10+
11+ /**
12+ * @param {number[] } matchsticks
13+ * @return {boolean }
14+ */
15+ var makesquare = function ( matchsticks ) {
16+ let sides = new Array ( 4 ) . fill ( 0 ) , ans = false , size = 0 ;
17+
18+ for ( let i = 0 ; i < matchsticks . length ; i ++ ) {
19+ size += matchsticks [ i ] ;
20+ }
21+ let max_size = size / 4 ;
22+ if ( ( max_size - Math . floor ( max_size ) ) !== 0 ) return false ;
23+
24+ matchsticks = matchsticks . sort ( ( a , b ) => b - a ) ;
25+
26+ function backtrack ( i ) {
27+ if ( ans ) return ;
28+ if ( i >= matchsticks . length ) {
29+ if ( check ( sides ) ) {
30+ ans = true ;
31+ }
32+ return ;
33+ }
34+ for ( let j = 0 ; j < 4 ; j ++ ) {
35+ if ( sides [ j ] + matchsticks [ i ] > max_size ) {
36+ continue ;
37+ }
38+ sides [ j ] += matchsticks [ i ] ;
39+
40+ backtrack ( i + 1 ) ;
41+ sides [ j ] -= matchsticks [ i ] ;
42+ }
43+ }
44+ backtrack ( 0 ) ;
45+
46+ return ans ;
47+ } ;
You can’t perform that action at this time.
0 commit comments