Skip to content

Commit 867ac44

Browse files
473-matchsticks to square
Sorry for uploading a duplicate last time! if there is a better implementation or one already existing, altho i did double check this time, feel free to delete.
1 parent fba5671 commit 867ac44

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
var makesquare = function(matchsticks) {
12+
let sides = new Array(4).fill(0), ans = false, size = 0;
13+
14+
for(let i = 0; i < matchsticks.length; i++){
15+
size += matchsticks[i];
16+
}
17+
let max_size = size / 4;
18+
if((max_size - Math.floor(max_size)) !== 0)return false;
19+
20+
matchsticks = matchsticks.sort((a,b)=>b-a);
21+
22+
function backtrack(i){
23+
if(ans)return;
24+
if(i >= matchsticks.length){
25+
if(check(sides)){
26+
ans = true;
27+
}
28+
return;
29+
}
30+
for(let j = 0; j < 4; j++){
31+
if(sides[j] + matchsticks[i] > max_size){
32+
continue;
33+
}
34+
sides[j] += matchsticks[i];
35+
36+
backtrack(i + 1);
37+
sides[j] -= matchsticks[i];
38+
}
39+
}
40+
backtrack(0);
41+
42+
return ans;
43+
};

0 commit comments

Comments
 (0)