Matchsticks to Square LeetCode solution in Python

1
class Solution:
2
def makesquare(self, matchsticks: List[int]) -> bool:
3
target, m = divmod(sum(matchsticks), 4)
4
if m:
5
return False
6
targetLst = [0] * 4
7
length = len(matchsticks)
8
matchsticks.sort(reverse=True)
9

10
def bt(i):
11
if i == length:
12
return len(set(targetLst)) == 1
13
for j in range(4):
14
if matchsticks[i] + targetLst[j] > target:
15
continue
16
targetLst[j] += matchsticks[i]
17
if bt(i + 1):
18
return True
19
targetLst[j] -= matchsticks[i]
20
if not targetLst[j]:
21
break
22
return False
23

24
return matchsticks[0] <= target and bt(0)

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0