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;
	}
}
相关推荐
星夜98217 分钟前
C++回顾 Day6
开发语言·数据结构·c++·算法
琢磨先生David1 小时前
责任链模式:构建灵活可扩展的请求处理体系(Java 实现详解)
java·设计模式·责任链模式
-曾牛2 小时前
使用Spring AI集成Perplexity AI实现智能对话(详细配置指南)
java·人工智能·后端·spring·llm·大模型应用·springai
Xiao Ling.2 小时前
设计模式学习笔记
java
MyikJ3 小时前
Java面试:从Spring Boot到分布式系统的技术探讨
java·大数据·spring boot·面试·分布式系统
louisgeek4 小时前
Java 插入排序之希尔排序
java
小兵张健4 小时前
用户、资金库表和架构设计
java·后端·架构
洛小豆4 小时前
ConcurrentHashMap.size() 为什么“不靠谱”?答案比你想的复杂
java·后端·面试
asom224 小时前
LeetCode Hot100(矩阵)
算法·leetcode·矩阵
蒟蒻小袁4 小时前
力扣面试150题--二叉树的右视图
算法·leetcode·面试