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;
	}
}
相关推荐
搞不懂语言的程序员2 小时前
Spring源码解析 - SpringApplication run流程-refreshContext(context)源码分析
java·spring
_hermit:2 小时前
【从零开始java学习|第三篇】变量与数据类型的关联
java·学习
sql2008help5 小时前
使用spring-boot-starter-validation实现入参校验
java·开发语言
Mr_Air_Boy5 小时前
springboot集成xxl-job
java·spring boot·spring
Babybreath-6 小时前
Tomcat
java·tomcat
摇滚侠6 小时前
面试实战 问题二十三 如何判断索引是否生效,什么样的sql会导致索引失效
java
悟纤7 小时前
当生产环境卡成 PPT:Spring Boot 线程 Dump 捉妖指南 - 第544篇
java·spring boot·后端
智驱力人工智能8 小时前
工厂智慧设备检测:多模态算法提升工业安全阈值
人工智能·算法·安全·边缘计算·智慧工厂·智能巡航·工厂设备检测
江影影影8 小时前
Spring Boot 2.6.0+ 循环依赖问题及解决方案
java·spring boot·后端
茴香豆的茴19 小时前
转码刷 LeetCode 笔记[2]:203. 移除链表元素(python)
笔记·leetcode·链表