2022-06-01 回溯

191 阅读1分钟

火柴拼正方形

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

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

个人题解

import java.util.Arrays;

public class Solution {
    private int[] matchsticksArray;
    private int sideLength;

    public boolean makesquare(int[] matchsticks) {
        int sum = Arrays.stream(matchsticks).sum();

        if (sum % 4 != 0) {
            return false;
        }

        Arrays.sort(matchsticks);

        sideLength = sum / 4;

        if (matchsticks[matchsticks.length - 1] > sideLength) {
            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;
        }
        matchsticksArray = matchsticks;

        int[] edges = new int[4];

        return backStack(0, edges);

    }

    private boolean backStack(int index, int[] edges) {
        if (index == matchsticksArray.length) {
            return true;
        }

        for (int i = 0; i < 4; i++) {
            edges[i] += matchsticksArray[index];
            if (edges[i] <= sideLength && backStack(index + 1, edges)) {
                return true;
            }
            edges[i] -= matchsticksArray[index];
        }

        return false;
    }
}