473. Matchsticks to Square
Posted cznczai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了473. Matchsticks to Square相关的知识,希望对你有一定的参考价值。
https://www.acwing.com/solution/LeetCode/content/3785/
class Solution
private boolean flag;
public boolean makesquare(int[] nums)
int temp = 0;
for (int i = 0; i < nums.length; i++)
temp += nums[i];
if (nums.length == 0 || temp % 4 != 0)
return false;
int count[] = new int[4];
Arrays.sort(nums);
dfs(nums, count, nums.length-1,temp/4);
return flag;
private void dfs(int[] nums, int[] count, int x,int avg)
if (x == -1)
for (int i = 0; i < 3; i++)
if (count[i] != count[i + 1])
return;
flag = true;
else
count[0] += nums[x];
if(count[0]<=avg)dfs(nums, count, x - 1,avg);
count[0] -= nums[x];
count[1] += nums[x];
if(count[1]<=avg)dfs(nums, count, x - 1,avg);
count[1] -= nums[x];
count[2] += nums[x];
if(count[2]<=avg)dfs(nums, count, x - 1,avg);
count[2] -= nums[x];
count[3] += nums[x];
if(count[3]<=avg)dfs(nums, count, x - 1,avg);
count[3] -= nums[x];
以上是关于473. Matchsticks to Square的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 473 - Matchsticks to Square - Medium (Python)
[LeetCode] Matchsticks to Square 火柴棍组成正方形
Matchsticks to Square && Grammar: reverse an primative array
Leetcode: Matchsticks to Square && Grammar: reverse an primative array