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;
	}
}
相关推荐
DoraBigHead1 小时前
小哆啦解题记——异位词界的社交网络
算法
麦兜*1 小时前
Spring Boot 企业级动态权限全栈深度解决方案,设计思路,代码分析
java·spring boot·后端·spring·spring cloud·性能优化·springcloud
木头左2 小时前
逻辑回归的Python实现与优化
python·算法·逻辑回归
ruan1145142 小时前
MySQL4种隔离级别
java·开发语言·mysql
Hellyc6 小时前
基于模板设计模式开发优惠券推送功能以及对过期优惠卷进行定时清理
java·数据库·设计模式·rocketmq
lifallen6 小时前
Paimon LSM Tree Compaction 策略
java·大数据·数据结构·数据库·算法·lsm-tree
hdsoft_huge6 小时前
SpringBoot 与 JPA 整合全解析:架构优势、应用场景、集成指南与最佳实践
java·spring boot·架构
百锦再7 小时前
详细解析 .NET 依赖注入的三种生命周期模式
java·开发语言·.net·di·注入·模式·依赖
程序员的世界你不懂7 小时前
基于Java+Maven+Testng+Selenium+Log4j+Allure+Jenkins搭建一个WebUI自动化框架(2)对框架加入业务逻辑层
java·selenium·maven
web_Hsir8 小时前
vue3.2 前端动态分页算法
前端·算法