【LeetCode】火柴拼正方形Java题解

132 阅读2分钟

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

题目描述

你将得到一个整数数组 matchsticks ,其中 matchsticks[i] 是第 i 个火柴棒的长度。你要用 所有的火柴棍 拼成一个正方形。你 不能折断 任何一根火柴棒,但你可以把它们连在一起,而且每根火柴棒必须 使用一次 。

如果你能使这个正方形,则返回 true ,否则返回 false 。

示例 1:

输入: matchsticks = [1,1,2,2,2]
输出: true
解释: 能拼成一个边长为2的正方形,每边两根火柴。

示例 2:

输入: matchsticks = [3,3,3,3,4]
输出: false
解释: 不能用所有火柴拼成一个正方形。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/matchsticks-to-square
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路分析

  • 今天是六一儿童节,本想着简单快乐一下,打开每日一题,今天的题目一点都不简单,还需继续努力,加油!
  • 火柴拼正方形题目,我们小时候玩过的一个游戏,游戏很好玩。这个题目中的关键点是你 不能折断 任何一根火柴棒,但你可以把它们连在一起,而且每根火柴棒必须 使用一次。我们可以首先将整个数组求和,除以4,求出正方形的边长。
  • 确定正方形的边长之后,我们可以采用回溯的思想解决问题,定义 edgesLength 为正方形的边长,定义edges数组为正方形,然后我们回溯搜索整个数组,得到答案。需要注意的是,我们可以先将matchsticks数组倒序排序,效率更高。下面实现代码参考题解,与你分享。

通过代码

class Solution {
    public boolean makesquare(int[] matchsticks) {
        int totalLen = Arrays.stream(matchsticks).sum();
        if (totalLen % 4 != 0) {
            return false;
        }
        Arrays.sort(matchsticks);
        int n = matchsticks.length;
        if (matchsticks[n - 1] > totalLen / 4) {
            return false;
        }

        for (int i = 0, j = n - 1; i < j; i++, j--) {
            int temp = matchsticks[i];
            matchsticks[i] = matchsticks[j];
            matchsticks[j] = temp;
        }

        int[] edges = new int[4];
        return dfs(0, matchsticks, n, edges, totalLen / 4);
    }

    public boolean dfs(int index, int[] matchsticks, int matchsticksLength, int[] edges, int edgesLength) {
        if (index == matchsticksLength) {
            return true;
        }
        for (int i = 0; i < edges.length; i++) {
            edges[i] += matchsticks[index];
            if (edges[i] <= edgesLength && dfs(index + 1, matchsticks, matchsticksLength, edges, edgesLength)) {
                return true;
            }
            edges[i] -= matchsticks[index];
        }
        return false;
    }
}

image.png

总结

  • 上述算法的时间复杂度是O(4 n),空间复杂度是O(n)
  • 坚持算法每日一题,加油!