You are given an integer list matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You may not break any stick, but you can join sticks end to end, and each matchstick must be used exactly one time.
Return True if you can make this square and False otherwise.
Function Signature
def can_make_square(matchsticks: list[int]) -> bool:
Rules
-
Every stick belongs to exactly one of the four sides, and a side's length is the sum of the sticks on it.
-
All four sides must have the same length.
Constraints
-
1 <= len(matchsticks) <= 15
-
1 <= matchsticks[i] <= 10^8
Examples
Input: matchsticks = [1, 1, 2, 2, 2]
Output: True
The total is 8, so each side must be 2. The sides [2], [2], [2] and [1, 1] all have length 2.
Input: matchsticks = [3, 3, 3, 3, 4]
Output: False
The total is 16 and the side must be 4. The stick of length 4 fills one side alone, but a side built from 3s is either 3 (too short) or at least 6 (too long), so the other three sides cannot be formed.
Input: matchsticks = [5, 5, 5, 5, 4, 4, 4, 4, 3, 3, 3, 3]
Output: True
The total is 48, so each side must be 12. Four sides of 5 + 4 + 3 use every stick once.