Matchsticks to Square
You are given an integer array matchsticks
where matchsticks[i]
is the length of the ith
matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
Return true
if you can make this square and false
otherwise.
Example 1:

Input: matchsticks = [1,1,2,2,2] Output: true Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.
Example 2:
Input: matchsticks = [3,3,3,3,4] Output: false Explanation: You cannot find a way to form a square with all the matchsticks.
Constraints:
1 <= matchsticks.length <= 15
1 <= matchsticks[i] <= 108
class Solution:
def isPossible(self, i, sides, matchsticks, n, total):
if i >= n:
return len(set(sides)) == 1
key = tuple(sorted(sides) + [i])
if key in self.cache:
return self.cache[key]
for j in range(4):
if 4 * (sides[j] + matchsticks[i]) > total:
continue
sides[j] += matchsticks[i]
curr = self.isPossible(i + 1, sides, matchsticks, n, total)
if curr:
self.cache[key] = True
return True
else:
sides[j] -= matchsticks[i]
self.cache[key] = False
return False
def makesquare(self, matchsticks: List[int]) -> bool:
matchsticks.sort(reverse = True)
n = len(matchsticks)
total = sum(matchsticks)
self.cache = {}
sides = [0, 0, 0, 0]
return self.isPossible(0, sides, matchsticks, n, total)
Comments
Post a Comment