美文网首页
LeetCode 第473题:火柴拼正方形

LeetCode 第473题:火柴拼正方形

作者: 放开那个BUG | 来源:发表于2024-05-01 13:21 被阅读0次

1、前言

题目描述

2、思路

3、代码

class Solution {
    public boolean makesquare(int[] matchsticks) {
        int total = 0;
        for (int num : matchsticks) {
            total += num;
        }
        if(total == 0 || total % 4 != 0){
            return false;
        }
        Arrays.sort(matchsticks);
        return backTrack(matchsticks, 0, total / 4, new int[4]);
    }

    private boolean backTrack(int[] nums, int index, int target, int[] size){
        if(index == nums.length){
            if(size[0] == size[1] && size[1] == size[2] && size[2] == size[3]){
                return true;
            }
            return false;
        }

        for(int i = 0; i < size.length; i++){
            if(size[i] + nums[index] > target){
                continue;
            }
            size[i] += nums[index];
            if(backTrack(nums, index + 1, target, size)){
                return true;
            }
            size[i] -= nums[index];
        }
        return false;
    }
}

相关文章

  • leetcode698 划分为k个相等的子集

    题目 划分为k个相等的子集 分析 这个题目跟leetcode473 火柴拼正方形的解法一样,这道题也可以叫做火柴拼...

  • Leetcode【473、698】

    问题描述:【Greedy+DFS】473. Matchsticks to Square 解题思路: 火柴拼正方形。...

  • LeetCode 473. 火柴拼正方形

    题目 473. 火柴拼正方形 题目描述 还记得童话《卖火柴的小女孩》吗?现在,你知道小女孩有多少根火柴,请找出一种...

  • LeetCode 473. 火柴拼正方形

    1、题目 火柴拼正方形 - 力扣(LeetCode) https://leetcode-cn.com/proble...

  • Leetcode 473. 火柴拼正方形 (Java实现)

    题目描述 题目来源 还记得童话《卖火柴的小女孩》吗?现在,你知道小女孩有多少根火柴,请找出一种能使用所有火柴拼成一...

  • 473. 火柴拼正方形

    还记得童话《卖火柴的小女孩》吗?现在,你知道小女孩有多少根火柴,请找出一种能使用所有火柴拼成一个正方形的方法。不能...

  • 473. 火柴拼正方形

    你将得到一个整数数组 matchsticks ,其中 matchsticks[i] 是第 i个火柴棒的长度。你要用...

  • 每日一题-473. 火柴拼正方形

    你将得到一个整数数组 matchsticks ,其中 matchsticks[i] 是第 i 个火柴棒的长度。你要...

  • T473、火柴拼正方形

    还记得童话《卖火柴的小女孩》吗?现在,你知道小女孩有多少根火柴,请找出一种能使用所有火柴拼成一个正方形的方法。不能...

  • LeetCode No.23 火柴拼正方形

    1.LeetCode473题目链接 https://leetcode-cn.com/problems/matchs...

网友评论

      本文标题:LeetCode 第473题:火柴拼正方形

      本文链接:https://www.haomeiwen.com/subject/jrlnxjtx.html