算法分析与设计第十二周:473. Matchsticks to Square

Description:
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 used exactly one 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.


代码:

class Solution(object):
    def makesquare(self, nums):
        if len(nums) <= 3:
            return False

        res = sum(nums)
        if res % 4 != 0:
            return False

        #sort the array in descending order to decrease the times of searching 
        nums.sort(key = lambda x : -x)
        cnt = 0
        side = res >> 2
        if nums[-1] > side:
            return False

        def rec(size, length, index , nums, res):
            if index == size:
                return res[0] == res[1] and res[1] == res[2] and res[2] == res[3] and res[0] == length
            for i in range(4):
                j = i - 1
                hasSearched = False
                #if the length has been searched before, just continue and stop searching for this length
                while j >= 0:
                    if res[i] == res[j]:
                        hasSearched = True
                    break
                if hasSearched:
                    continue
                if res[i] + nums[index]> length:
                    #if the last length can't reach the target length, just return False and stop searching for the remaining matches
                    if i == 3 and res[i] != length:
                        return False
                    continue
                else:
                    res[i] += nums[index]
                    if rec(size, length, index + 1, nums, res):
                        return True
                    res[i] -= nums[index]

            return False

        return rec(len(nums), side, 0, nums, [0, 0, 0, 0])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值