




Sponsored
Sponsored
This approach involves using backtracking to attempt fitting matchsticks into four equal-length sides. First, calculate the potential side length as the total sum of matchsticks divided by four. Each matchstick will be assigned to one of the four sides iteratively. If a proper combination is found, a square can be formed.
The matchsticks array is sorted in descending order to optimize the process, ensuring that larger matchsticks are placed first. This reduces the number of recursive calls by filling up spaces more quickly.
Time Complexity: O(4^N), where N is the length of matchsticks and 4 is because each matchstick could theoretically fit into one of four sides.
Space Complexity: O(N) due to the recursion stack.
1def makesquare(matchsticks):
2    if len(matchsticks) < 4: return False
3    total_length = sum(matchsticks)
4    if total_length % 4 != 0: return False
5    sides = [0] * 4
6    matchsticks.sort(reverse=True)
7    
8    def backtrack(index):
9        if index == len(matchsticks):
10            return all(side == total_length // 4 for side in sides)
11        for i in range(4):
12            if sides[i] + matchsticks[index] <= total_length // 4:
13                sides[i] += matchsticks[index]
14                if backtrack(index + 1):
15                    return True
16                sides[i] -= matchsticks[index]
17        return False
18    
19    return backtrack(0)The Python solution uses a recursive function backtrack that attempts to assign each matchstick to one of the four sides. The search attempts adding the current matchstick to any side, and checks recursively if that yields a valid solution. The matchsticks array is sorted in descending order to try larger matchsticks first.
This approach leverages dynamic programming combined with bitmasking to efficiently explore combinations of matchsticks placed into sides. The DP state represents which matchsticks have been used, and the transition involves trying to extend the current side or start a new side once the correct length is reached.
Time Complexity: O(2^N * N), where N is the number of matchsticks, due to exploring all states.
Space Complexity: O(2^N) for memoization.
1var makesquare = function(matchsticks) {
The JavaScript solution mirrors the C++ dynamic programming approach with bitmasking. A map is used to memoize results for different states, indicated by the binary mask of used matchsticks. The logic attempts to add matchsticks to form sides of the expected length.