你将得到一个整数数组 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;
}



