473-matchsticks-to-square

Try it on leetcode

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(Python)

class Solution:
    def makesquare(self, matchsticks: List[int]) -> bool:
        return self.dp(matchsticks)

    """
    Time Complexity: O(4^n)
    Space Complexity: O(n)
    """

    def dfs(self, matchsticks: List[int]) -> bool:
        if not matchsticks:
            return False

        length = sum(matchsticks) // 4

        if sum(matchsticks) / 4 != length:
            return False

        matchsticks.sort(reverse=True)
        sides = [0] * 4

        def backtrack(i):
            if i == len(matchsticks):
                return True

            for j in range(4):
                if sides[j] + matchsticks[i] <= length:
                    sides[j] += matchsticks[i]
                    if backtrack(i + 1):
                        return True
                    sides[j] -= matchsticks[i]

            return False

        return backtrack(0)

    """
    Time Complexity: O(n*2^n)
    Space Complexity: O(n+2^n)
    """

    def dp(self, matchsticks: List[int]) -> bool:
        if not matchsticks:
            return False

        lth = len(matchsticks)

        perimeter = sum(matchsticks)
        side = perimeter // 4

        if side * 4 != perimeter:
            return False

        dp = {}

        def recur(mask, sidesfilledsofar):
            total = 0

            for i in range(lth - 1, -1, -1):
                if not (mask & (1 << i)):
                    total += matchsticks[lth - 1 - i]

            if total > 0 and total % side == 0:
                sidesfilledsofar += 1

            if sidesfilledsofar == 3:
                return True

            if (mask, sidesfilledsofar) in dp:
                return dp[(mask, sidesfilledsofar)]

            ans = False

            remainingspace = side * (int(total / side) + 1) - total

            for i in range(lth - 1, -1, -1):
                if matchsticks[lth - 1 - i] <= remainingspace and mask & (1 << i):
                    if recur(mask ^ (1 << i), sidesfilledsofar):
                        ans = True
                        break
            dp[(mask, sidesfilledsofar)] = ans
            return ans

        return recur((1 << lth) - 1, 0)