问题:数组
Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.ide
Your input will be several matchsticks the girl has, represented with their stick length. Your output will either be true or false, to represent whether you could make one square using all the matchsticks the little match girl has.spa
Example 1:code
Input: [1,1,2,2,2] Output: true Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.
Example 2:orm
Input: [3,3,3,3,4] Output: false Explanation: You cannot find a way to form a square with all the matchsticks.
Note:排序
0
to 10 ^ 9
.15
.解决:递归
① 跟以前有道题Partition Equal Subset Sum有点像,那道题问咱们能不能将一个数组分红和相等的两个子数组,而这道题其实是让咱们将一个数组分红四个和相等的子数组。get
先给数组从大到小的顺序排序,这样大的数字先加,若是超过target了,就直接跳过了后面的再次调用递归的操做。input
咱们创建一个长度为4的数组sums来保存每一个边的长度和,咱们但愿每条边都等于target,数组总和的四分之一。而后咱们遍历sums中的每条边,咱们判断若是加上数组中的当前数字大于target,那么咱们跳过,若是没有,咱们就加上这个数字,而后对数组中下一个位置调用递归,若是返回为真,咱们返回true,不然咱们再从sums中对应位置将这个数字减去继续循环。it
class Solution { //39ms public boolean makesquare(int[] nums) { if (nums == null || nums.length < 4) return false; int sum = 0; for (int n : nums){ sum += n; } if (sum % 4 != 0) return false; int[] sums = new int[4]; Arrays.sort(nums); return dfs(nums,sums,nums.length - 1,sum / 4); } public boolean dfs(int[] nums,int[] sums,int i,int target){ if (i < 0){ return sums[0] == target && sums[1] == target && sums[2] == target; } for (int j = 0;j < 4;j ++){ if (sums[j] + nums[i] > target) continue; sums[j] += nums[i]; if (dfs(nums,sums,i - 1,target)) return true; sums[j] -= nums[i]; } return false; } }