【10月打卡~Leetcode每日一题】473. 火柴拼正方形(难度:中等)

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)

注意进行剪枝,其中比较关键的剪枝是将数组从大到小排序,本题等价于四个抽屉,往抽屉里放入相同量的球,所以如果先放大球的话,会提前终止很多错误的方案。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值