Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9846735

Browse files
authored
Create 473-Matchsticks-to-Square.py
1 parent 81c294e commit 9846735

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

473-Matchsticks-to-Square.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution:
2+
def makesquare(self, matchsticks: List[int]) -> bool:
3+
length = sum(matchsticks) // 4
4+
sides = [0] * 4
5+
6+
if sum(matchsticks) / 4 != length:
7+
return False
8+
matchsticks.sort(reverse=True)
9+
def backtrack(i):
10+
if i == len(matchsticks):
11+
return True
12+
13+
for j in range(4):
14+
if sides[j] + matchsticks[i] <= length:
15+
sides[j] += matchsticks[i]
16+
if backtrack(i + 1):
17+
return True
18+
sides[j] -= matchsticks[i]
19+
return False
20+
21+
return backtrack(0)

0 commit comments

Comments
 (0)