题目要求
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.
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.
Example 1:
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:
Input: [3,3,3,3,4]
Output: false
Explanation: You cannot find a way to form a square with all the matchsticks.
Note:
- The length sum of the given matchsticks is in the range of
0
to10^9
. - The length of the given matchstick array will not exceed
15
.
现有一个整数数组代表一堆各种长度的火柴。问这些火柴拼拼凑凑是否能够拼成一个正方形。要求每根火柴只能使用一次。
思路和代码
这里采用的是深度优先遍历的思路,即尝试将木棍分别放在每个边上,看看是否能够最终构成一个正方形。一个简单的优化方式是减少重复长度的火柴的分配。
public boolean makesquare(int[] nums) {if (nums == null || nums.length == 0){return false;}
int sum = 0;
int max = 0;
for (int num : nums) {
sum += num;
max = Math.max(num, max);
}
if (sum % 4 != 0) {return false;}
int sideLength = sum / 4;
if (max > sideLength) {return false;}
return makesquare(nums, 0, sideLength, sideLength, sideLength, sideLength);
}
public boolean makesquare(int[] nums, int index, int firstSide, int secondSide, int thirdSide, int fourthSide) {if (index >= nums.length) return true;
boolean canMake = false;
if (firstSide >= nums[index]) {firstSide -= nums[index];
canMake = makesquare(nums, index+1, firstSide, secondSide, thirdSide, fourthSide);
firstSide += nums[index];
}
if (!canMake && secondSide != firstSide && secondSide >= nums[index]) {secondSide -= nums[index];
canMake = makesquare(nums, index+1, firstSide, secondSide, thirdSide, fourthSide);
secondSide += nums[index];
}
if (!canMake && thirdSide != secondSide && thirdSide >= nums[index]) {thirdSide -= nums[index];
canMake = makesquare(nums, index+1, firstSide, secondSide, thirdSide, fourthSide);
thirdSide += nums[index];
}
if (!canMake && fourthSide != thirdSide && fourthSide >= nums[index]) {fourthSide -= nums[index];
canMake = makesquare(nums, index+1, firstSide, secondSide, thirdSide, fourthSide);
fourthSide += nums[index];
}
return canMake;
}