【LeetCode】473. 火柴拼正方形

226 阅读2分钟

image.png

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第13天,点击查看活动详情

测试岗位也越来卷了,除了基本的功能测试外,还要有编程基础、脚本经验才脱颖而出。

怎么才能提高我们的编程能力呢,刷LeetCode是最佳的途径之一,话不多数,刷题走起~

一、题目描述:

  • 题目内容

image.png

  • 题目示例

image.png

  • 题目解析

    • 1 <= matchsticks.length <= 15
    • 1 <= matchsticks[i] <= 108

二、思路分析:

我们拿到本题,读取题意要求对matchsticks数组中的火柴元素,进行拼接成正方形。从题目中,我们可以获取到两点信息:

  • 火柴元素不能被拆分
  • 正方形周长计算公式:4*边长

比如,根据示例1,matchsticks列表火柴元素,拼接成正方形过程如下:

image.png

首先,根据正方形的特点:4*边长,因此我们可以先通过 matchsticks的火柴长度是4的倍数

  • 正方形周长total:sum(matchsticks)
  • total % 4 != 0 则可以直接判断matchsticks里的元素不能拼接成正方形
  • 反之,我们还需要进行进一步的判断,如示例二:matchsticks = [3,3,3,3,4],也不能拼接成正方形

image.png

因此,要对matchsticks 每一个元素相加与正方形的边长进行比较判断,需要使用到dfs思想

  • 使用edge列表来存储正方形四个边,初始化为0
  • 使用递归方式,枚举每一根火柴的放置情况
class Solution(object):
    def makesquare(self, matchsticks):
        """
        :type matchsticks: List[int]
        :rtype: bool
        """
        total = sum(matchsticks)

        if total % 4 != 0:
            return False
        
        matchsticks = sorted(matchsticks,reverse=True)

        edge = [0]*4

        def dfs(index):

            if index == len(matchsticks):
                return True
            for i  in range(4):
               edge[i] += matchsticks[index]
               if edge[i] <= total // 4 and dfs(index+1):
                   return True
               edge[i] -= matchsticks[index]
            return False
        return dfs(0)

三、总结:

本题主要考察dfs深度优先算法,对matchsticks数组中每一根火柴放置情况进行回溯。AC代码提交记录如下:

image.png

  • 时间复杂度O(4**n),n为matchsticks数组长度
  • 空间复杂度:O(n)。递归栈需要占用 O(n)的空间。

以上是本期内容,欢迎大佬们点赞评论,下期见~~