-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0473-matchsticks-to-square.py
More file actions
31 lines (27 loc) · 961 Bytes
/
0473-matchsticks-to-square.py
File metadata and controls
31 lines (27 loc) · 961 Bytes
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
# time complexity: O(4^n)
# space complexity: O(n)
from typing import List
class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
n = len(matchsticks)
paremiter = sum(matchsticks)
side = paremiter // 4
if side * 4 != paremiter:
return False
sums = [0 for _ in range(4)]
matchsticks.sort(reverse=True)
def backtrack(idx: int):
if idx == n:
return sums[0] == sums[1] == sums[2] == side
for i in range(4):
if sums[i] + matchsticks[idx] <= side:
sums[i] += matchsticks[idx]
if backtrack(idx + 1):
return True
sums[i] -= matchsticks[idx]
return False
return backtrack(0)
matchsticks = [1, 1, 2, 2, 2]
print(Solution().makesquare(matchsticks))
matchsticks = [3, 3, 3, 3, 4]
print(Solution().makesquare(matchsticks))