Comment on page
473 Matchsticks to Square
Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be usedexactlyone time.
Your input will be several matchsticks the girl has, represented with their stick length. Your output will either be true or false, to represent whether you could make one square using all the matchsticks the little match girl has.
You can form a square with length 2, one side of the square came two sticks with length 1.
You cannot find a way to form a square with all the matchsticks.
- 1.The length sum of the given matchsticks is in the range of 0 to 10^9.
- 2.The length of the given matchstick array will not exceed 15.
The Idea: Abstractly, this problem is equivalent to the partition problem, which aims to determine whether a multi-set can be partitioned into 2 groups, where the sums are the same. In this problem, every match stick has the option of following into 1 or 4 groups, and each group (which sums up to the perimeter length of one side) should add up to one of the respective sides (sum/4). We can perform a few checks first, like identifying that the total sum should some factor of 4, and that no match stick is greater than the greatest possible length it could be (sum/4). Sorting additionally ensures that we converge to a solution faster.
Complexity: O(n*4^n) time and O(n) space
def makesquare(self, nums):
:type nums: List[int]
sum_nums = sum(nums)
if sum_nums % 4 != 0 or not nums:
target_len = sum_nums / 4
if nums[-1] > target_len:
def dfs(target, groups, index):
if index == len(nums):
if all([g == target for g in groups]):
for j in range(len(groups)):
num = nums[index]
if groups[j] + num > target:
groups[j] += num
if dfs(target, groups, index + 1):
groups[j] -= num
return dfs(target_len,  * 4, 0)