Matchsticks to Square
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.
public class Solution {
public boolean makesquare(int[] nums) {
if(nums.length < 4) return false;
int sum = 0;
for(int num: nums) sum += num;
if(sum % 4 != 0) return false;
return dfs(nums, 0, new int[4], sum / 4);
}
public boolean dfs(int[] nums, int start, int[] sums, int target) {
if(start == nums.length) {
return sums[0] == target && sums[1] == target && sums[2] == target && sums[3] == target;
}
for(int i = 0; i < 4; i ++) {
if(sums[i] + nums[start] > target) continue;
sums[i] += nums[start];
if(dfs(nums, start + 1, sums, target)) return true;
sums[i] -= nums[start];
}
return false;
}
}