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
Solutions
Solution 1
Thinking
A square needs a total divisible by \(4\) and no stick longer than a side. Assigning \(n\le 15\) sticks to four sides is \(4^n\) without pruning.
Place large sticks first: try each side that would not overflow, and skip a side equal to the previous one. Fail immediately on a bad total or a too-long stick.
Large sticks overflow sooner; equal-side skipping removes symmetric states.
Side-by-side backtracking still repeats partitions. A bit mask of used sticks plus the current side sum \(t\) is enough: a legal stick updates \(t\gets (t+v)\bmod s\). After sorting, \(t+v>s\) cuts the rest of the loop.
Memoizing \((\textit{mask},t)\) folds duplicate partitions into \(O(n\,2^n)\).