Skip to content

473. Matchsticks to Square

Difficulty Topics

Description

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

Solution

matchsticks-to-square.py
class Solution:
    def makesquare(self, matchsticks: List[int]) -> bool:
        n = len(matchsticks)
        total = sum(matchsticks)
        if total % 4 != 0: return False
        target = total // 4
        matchsticks.sort(reverse = 1)

        @cache
        def go(mask):
            curr = 0

            for i in range(n):
                if (mask >> i) & 1 > 0:
                    curr += matchsticks[i]

            done, side = divmod(curr, target)

            if done == 3: return True

            for i in range(n):
                if (mask & (1 << i)) == 0:
                    if side + matchsticks[i] <= target and go(mask | (1 << i)):
                        return True

            return False

        return go(0)