Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5758600

Browse files
Create Solution.py
1 parent 7719c39 commit 5758600

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

‎Matchsticks to Square/Solution.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution:
2+
def makesquare(self, matchsticks: List[int]) -> bool:
3+
N = len(matchsticks)
4+
basket, rem = divmod(sum(matchsticks), 4)
5+
if rem or max(matchsticks) > basket: return False
6+
7+
@lru_cache(None)
8+
def dfs(mask):
9+
if mask == 0: return 0
10+
for j in range(N):
11+
if mask & 1<<j:
12+
neib = dfs(mask ^ 1<<j)
13+
if neib >= 0 and neib + matchsticks[j] <= basket:
14+
return (neib + matchsticks[j]) % basket
15+
return -1
16+
17+
return dfs((1<<N) - 1) == 0

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /