MCPcopy Create free account
hub / github.com/neetcode-gh/leetcode / makesquare

Function makesquare

javascript/0473-matchsticks-to-square.js:15–49  ·  view source on GitHub ↗
(matchsticks)

Source from the content-addressed store, hash-verified

13 * @return {boolean}
14 */
15var makesquare = function (matchsticks) {
16 let sides = new Array(4).fill(0),
17 ans = false,
18 size = 0;
19
20 for (let i = 0; i < matchsticks.length; i++) {
21 size += matchsticks[i];
22 }
23 let max_size = size / 4;
24 if (max_size - Math.floor(max_size) !== 0) return false;
25
26 matchsticks = matchsticks.sort((a, b) => b - a);
27
28 function backtrack(i) {
29 if (ans) return;
30 if (i >= matchsticks.length) {
31 if (check(sides)) {
32 ans = true;
33 }
34 return;
35 }
36 for (let j = 0; j < 4; j++) {
37 if (sides[j] + matchsticks[i] > max_size) {
38 continue;
39 }
40 sides[j] += matchsticks[i];
41
42 backtrack(i + 1);
43 sides[j] -= matchsticks[i];
44 }
45 }
46 backtrack(0);
47
48 return ans;
49};

Callers

nothing calls this directly

Calls 1

backtrackFunction · 0.70

Tested by

no test coverage detected