473. Matchsticks to Square

Medium (Trung bình) Python 🔗 Xem trên LeetCode

📋 Đề Bài

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

🧠 Thuật Toán & Kỹ Thuật

Sorting (Sắp xếp)Backtracking (Quay lui)
⏱️ Thời gian O(n log n)
💾 Không gian O(n)

💻 Lời Giải

Python 0473-matchsticks-to-square.py
class Solution:
    def makesquare(self, matchsticks: List[int]) -> bool:
        total = sum(matchsticks)
        
        if total % 4 != 0:
            return False
        
        n = len(matchsticks)
        k = 4
        self.d = total // k
        flags = [0] * k
        self.check = False
        matchsticks.sort(reverse = True)
        
        def backTracking(i):
            if self.check:
                return
            
            if i == n:
                self.check = True
                return
            
            seen = set()
            
            for j in range(k):
                if flags[j] in seen:
                    continue
                if flags[j] + matchsticks[i] > self.d:
                    continue
                seen.add(flags[j])
                flags[j] += matchsticks[i]
                backTracking(i + 1)
                flags[j] -= matchsticks[i]
                
        backTracking(0)
                
        return self.check