Skip to content
BytePatterns

Matchsticks Into a Square

HardBacktracking#backtracking#pruning#k-way-partition~40m

Problem

You have a set of matchsticks with integer lengths. Decide whether you can use every stick exactly once, without breaking any, to form the outline of a square. There are between 1 and 15 sticks and each length is between 1 and 10^8. Trying all 4^15 ways to assign sticks to sides is about a billion cases, so the search must prune aggressively.

Examples

Input:  sticks = [1, 1, 2, 2, 2]
Output: True
Why:    the sides are 2, 2, 2 and 1 + 1
Input:  sticks = [3, 3, 3, 3, 4]
Output: False
Why:    the total, 16, would need sides of 4, and the four 3s cannot reach 4 without breaking
Input:  sticks = [5, 5, 5, 5, 4, 4, 4, 4, 3, 3, 3, 3]
Output: True
Why:    every side is 5 + 4 + 3

Hints

0 / 3

Stuck on the idea rather than the code? Word Search & Pruning covers it.