473. Matchsticks to Square
Last updated
Last updated
/**
* Time complexity :
* Space complexity :
*/
class Solution {
public boolean makesquare(int[] matchsticks) {
if(matchsticks == null || matchsticks.length < 4) {
return false;
}
int sum = 0;
for(int matchstick: matchsticks) {
sum += matchstick;
}
if(sum%4 != 0) {
return false;
}
return makesquare(matchsticks, 0, sum/4, new int[4]);
}
private boolean makesquare(int[] matchsticks, int index, int target, int[] sides) {
if(index == matchsticks.length) {
if(sides[0] == target && sides[1] == target &&
sides[2] == target && sides[3] == target) {
return true;
}
return false;
}
for(int i = 0; i < 4; i++) {
if(sides[i] + matchsticks[index] > target) {
continue;
}
sides[i] += matchsticks[index];
if(makesquare(matchsticks, index+1, target, sides)) {
return true;
}
sides[i] -= matchsticks[index];
}
return false;
}
}