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]; } } }