473. 火柴拼正方形

473. 火柴拼正方形

原题链接:

473. 火柴拼正方形

https://leetcode.cn/problems/matchsticks-to-square/description/

完成情况:

解题思路:

参考代码:

java 复制代码
package 西湖算法题解___中等题;

import java.util.Arrays;

public class __473火柴拼正方形 {
	//你要用 所有的火柴棍 拼成一个正方形。你 不能折断 任何一根火柴棒
	public boolean makesquare(int[] matchsticks) {
		int sum = 0;
		int nLength = matchsticks.length;
		if (nLength<4){
			return false;
		}
		sum = Arrays.stream(matchsticks).sum(); //调用Arrays.stream去进行求和。
		for (int num:matchsticks){
			sum+=num;
		}
		if (sum%4 != 0){
			return false;
		}
		//接下来就是将数组顺序化,然后进行匹配,看是否每次都能找到满足边长要求的对应长度的【数组元素和】去累加获取。
		Arrays.sort(matchsticks);
		for (int i=0,j = matchsticks.length-1;i<j;i++,j--){
			if (matchsticks[j] > sum/4){    //如果最后的元素,甚至大于总数的四分之一,肯定组成不了正方形了。
				return false;
			}
			int temp = matchsticks[i];
			matchsticks[i] = matchsticks[j];
			matchsticks[j] = temp;
		}
		int edges [] = new  int[4];
		return dfs_makesquare(0,matchsticks,edges,sum/4);
	}

	/**
	 *
	 * @param index
	 * @param matchsticks
	 * @param edges
	 * @param meanLen
	 * @return
	 */
	private boolean dfs_makesquare(int index, int[] matchsticks, int[] edges, int meanLen) {
		if (index == matchsticks.length){
			return true;
		}
		for (int i=0;i<edges.length;i++){
			edges[i] += matchsticks[index];
			if (edges[i] <= meanLen && dfs_makesquare(index+1,matchsticks,edges,meanLen)){
				return true;
			}
			edges[i] -= matchsticks[index];
		}
		return false;
	}
}
相关推荐
苏言の狗10 分钟前
小R的并集大小期望计算 | 蛮力
数据结构·算法
BineHello16 分钟前
MPC用优化求解器 - 解决无人机轨迹跟踪
算法·矩阵·自动驾驶·动态规划·无人机
誓约酱19 分钟前
(每日一题) 力扣 14 最长公共前缀
算法·leetcode·职场和发展
用户611881615196224 分钟前
Java基础面试题
java
DavidSoCool1 小时前
Elasticsearch Java API Client [8.17] 使用
java·大数据·elasticsearch
无世世1 小时前
【Java从入门到起飞】面向对象编程(高级)
java·开发语言
Vic101011 小时前
Mac如何查看 IDEA 的日志文件
java·macos·intellij-idea
陈逸轩*^_^*1 小时前
idea打不开,idea打不开,Error occurred during initialization of VM
java·ide·intellij-idea
冠位观测者1 小时前
【Leetcode 每日一题 - 补卡】2070. 每一个查询的最大美丽值
数据结构·算法·leetcode
=PNZ=BeijingL1 小时前
使用Mockito实现单元测试
java