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

来源:互联网 发布:java时间戳转换为date 编辑:程序博客网 时间:2024/05/14 07:47

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
原创粉丝点击