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;
	}
}
相关推荐
Q_970956399 分钟前
java+vue+SpringBoo校园失物招领网站(程序+数据库+报告+部署教程+答辩指导)
java·数据库·vue.js
Wyc7240917 分钟前
Maven
java·数据库·maven
军训猫猫头18 分钟前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
程序猿小D20 分钟前
[附源码+数据库+毕业论文]基于Spring+MyBatis+MySQL+Maven+jsp实现的电影小说网站管理系统,推荐!
java·数据库·mysql·spring·毕业设计·ssm框架·电影小说网站
success32 分钟前
【爆刷力扣-数组】二分查找 及 衍生题型
算法
Orlando cron1 小时前
数据结构入门:链表
数据结构·算法·链表
木头没有瓜2 小时前
idea离线安装插件
java·ide·intellij-idea
llwszx2 小时前
Spring中DelayQueue深度解析:从原理到实战(附结构图解析)
java·后端·spring·delayqueue·延迟任务
牛客企业服务2 小时前
2025年AI面试推荐榜单,数字化招聘转型优选
人工智能·python·算法·面试·职场和发展·金融·求职招聘
述雾学java2 小时前
Spring Cloud Feign 整合 Sentinel 实现服务降级与熔断保护
java·spring cloud·sentinel