Skip to content

Commit 3447fc6

Browse files
authored
Merge pull request neetcode-gh#485 from hnlCaseSensitive/patch-3
473-matchsticks to square
2 parents fba5671 + 0c5b8a6 commit 3447fc6

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
};

0 commit comments

Comments
 (0)