forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0473-matchsticks-to-square.js
49 lines (43 loc) · 1.07 KB
/
0473-matchsticks-to-square.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function check(arr) {
let temp = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] !== temp) {
return false;
}
}
return true;
}
/**
* @param {number[]} matchsticks
* @return {boolean}
*/
var makesquare = function (matchsticks) {
let sides = new Array(4).fill(0),
ans = false,
size = 0;
for (let i = 0; i < matchsticks.length; i++) {
size += matchsticks[i];
}
let max_size = size / 4;
if (max_size - Math.floor(max_size) !== 0) return false;
matchsticks = matchsticks.sort((a, b) => b - a);
function backtrack(i) {
if (ans) return;
if (i >= matchsticks.length) {
if (check(sides)) {
ans = true;
}
return;
}
for (let j = 0; j < 4; j++) {
if (sides[j] + matchsticks[i] > max_size) {
continue;
}
sides[j] += matchsticks[i];
backtrack(i + 1);
sides[j] -= matchsticks[i];
}
}
backtrack(0);
return ans;
};