Problem 473: Matchsticks to Square
public class Solution {
public boolean makesquare(int[] nums) {
if (nums == null || nums.length < 4) return false;
int sum = 0;
for (int num : nums) {
sum += num;
}
if (sum % 4 != 0) return false;
Arrays.sort(nums);
reverse(nums);
return dfs(nums, new int[4], 0, sum / 4);
}
private boolean dfs(int[] nums, int[] sums, int count, int target) {
if (count == nums.length) {
if (sums[0] == target && sums[1] == target && sums[2] == target) return true;
}
for (int i = 0; i < 4; i++) {
if (sums[i] + nums[count] > target) continue;
sums[i] += nums[count];
if (dfs(nums, sums, count + 1, target)) return true;
sums[i] -= nums[count];
}
return false;
}
private void reverse(int[] nums) {
int len = nums.length;
for (int i = 0; i < len / 2; i++) {
int tmp = nums[i];
nums[i] = nums[len - 1 - i];
nums[len - 1 - i] = tmp;
}
}
}