DFS+回溯专题 - leetcode473. Matchsticks to Square★

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a786150017/article/details/83042675

473. Matchsticks to Square

总结
可以2sum,3sum, 4sum…头晕 - Mark代码不是最简的,待完善

题目描述

给定一些整数,代表火柴棍的长度。求这些火柴棍是否可以组成一个正方形。火柴棍不可以拆分,但是可以拼接。

例子
Example 1:

Input: [1,1,2,2,2]
Output: true

Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.
Example 2:

Input: [3,3,3,3,4]
Output: false

Explanation: You cannot find a way to form a square with all the matchsticks.

解法
很容易得到正方形的边长side;
建立一个长度为4的辅助数组subNums表示4条边的边长;
(截止条件) 前三条边长度都等于side,返回True
(主体) 尝试填充四条边,如果填充完了都无法返回True,则返回False
(剪枝):数组nums排序-O(nlogn);从大数开始操作,节省时间

解法
DFS

class Solution(object):
    def makesquare(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """   
        side = sum(nums) / 4
        if len(nums) < 4 or max(nums) > side or side * 4 != sum(nums):
            return False
        
        nums.sort(reverse = True)
        subNums = [side] * 4
        return self.dfs(nums, subNums, side, 0)
    
    def dfs(self, nums, subNums, side, idx):
        if idx == len(nums):
            return True
        
        num = nums[idx]
        for i in range(4):
            if subNums[i] >= num:
                subNums[i] -= num
                if self.dfs(nums, subNums, side, idx+1):
                    return True
                subNums[i] += num
        return False

猜你喜欢

转载自blog.csdn.net/a786150017/article/details/83042675