栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

LeetCode每日打卡 473. 火柴拼正方形

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode每日打卡 473. 火柴拼正方形

首先看题目介绍

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

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

示例:

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

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

解题思路

递归,贪心,深度优先,剪枝

四条边假设为4个固定容量的桶,每次尝试把每根火柴放入4个桶,全部放完则可以组成正方形。

    public static void main(String[] args) {
//        int[] matchsticks = {1,1,2,2,2};
        int[] matchsticks = {2,2,1,2,1};
//        int[] matchsticks = {3,3,3,3,4};
        boolean b = makesquare(matchsticks);
        System.out.println(b);
    }


    public static boolean makesquare(int[] matchsticks) {
        // 首先获得周长
        int sums = Arrays.stream(matchsticks).sum();
        // 周长不是4的整数必不可能组成正方形
        if (sums % 4 != 0) {
            return false;
        }
        // 获取到正方形的边长
        int length = sums / 4;
        // 如果最长的火柴长度大于边长,那么也不可能组成正方形
        for (int matchstick : matchsticks) {
            if (matchstick > length) {
                return false;
            }
        }
        // 进行降序排序
        for (int i = 0, j = matchsticks.length - 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, edges, length);
    }

    private static boolean dfs(int index, int[] matchsticks, int[] edges, int length) {
        if (index == matchsticks.length) {
            return true;
        }
        // 尝试把火柴放入四个桶中
        for (int i = 0; i < edges.length; i++) {
            // 进行剪枝,当前桶和上一个桶火柴数一致时,可以直接跳过
            if (i == 0 || edges[i] != edges[i - 1]) {
                // 尝试放入并开始放下一根火柴
                edges[i] += matchsticks[index];
                if (edges[i] <= length && dfs(index + 1, matchsticks, edges, length)) {
                    return true;
                }
                // 回溯
                edges[i] -= matchsticks[index];
            }
        }
        return false;
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/945037.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号