美文网首页leetcode算法
473. 火柴拼正方形

473. 火柴拼正方形

作者: 刘翊扬 | 来源:发表于2022-06-01 23:00 被阅读0次

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

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

示例1:

image.png

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

示例2:

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

提示:

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

方法:回溯算法

class Solution {
        public static boolean makesquare(int[] matchsticks) {
        int sum = 0, len = matchsticks.length;
        for (int matchstick : matchsticks) {
            sum += matchstick;
        }
        if (sum % 4 != 0) {
            return false;
        }
        // 排序
        Arrays.sort(matchsticks);
        return backtrace(matchsticks, sum >> 2, len - 1, new int[4]);
    }

    static boolean backtrace(int[] matchsticks, int target, int index, int[] size) {
        if (index == -1) {
            // 火柴用完了
            return size[0] == size[1] && size[1] == size[2] && size[2] == size[3];
        }
        for (int i = 0; i < 4; i++) {
            // size[i] == size[i - 1]即上一个分支的值和当前分支的一样,上一个分支没有成功,
            if (size[i] + matchsticks[index] > target || (i > 0 && size[i] == size[i - 1])) {
                continue;
            }
            //如果当前火柴放到size[i]这个边上,长度不大于target,我们就放上面
            size[i] += matchsticks[index];
            if (backtrace(matchsticks, target, index - 1, size)) {
                return true;
            }
            size[i] -= matchsticks[index];
        }
        return false;
    }
}

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

相关文章

网友评论

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

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