473. 火柴拼正方形
搜索+回溯(其实就是枚举
class Solution:
def makesquare(self, nums: List[int]) -> bool:
if not nums:
return False
total = sum(nums)
each = total >> 2
if each << 2 != total:
return False
nums.sort(reverse = True)
square = [0 for _ in range(4)]
def dfs(index):
if index == len(nums):
return square[0] == square[1] == square[2] == each
for i in range(4):
if square[i] + nums[index] <= each:
square[i] += nums[index]
if dfs(index+1):
return True
square[i] -= nums[index]
return False
return dfs(0)
时间复杂度O(n^4)
空间复杂度O(n)
注意进行剪枝,其中比较关键的剪枝是将数组从大到小排序,本题等价于四个抽屉,往抽屉里放入相同量的球,所以如果先放大球的话,会提前终止很多错误的方案。