//先求出和为edge的划分。再枚举划分,至多只需要枚举三个划分
import java.util.ArrayList;
import java.util.List;
class Solution {
int edge = 0;
List<Integer> stateList = new ArrayList<>();
int[] matchsticks;
public static void main(String[] args) {
Solution solution = new Solution();
solution.makesquare(new int[]{
2,2,2,2,2,6
});
}
public boolean makesquare(int[] matchsticks) {
this.edge = 0;
for (int u : matchsticks) {
edge += u;
}
if (edge % 4 != 0) {
return false;
}
edge = edge / 4;
this.matchsticks = matchsticks;
this.stateList = new ArrayList<>();
dfs(0, 0, 0);
int size = stateList.size();
for (int i = 0; i < size; i++) {
int statei = stateList.get(i);
for (int j = i + 1; j < size; j++) {
int statej = stateList.get(j);
if ((statei & statej) > 0) {
continue;
}
for (int k = j + 1; k < size; k++) {
int statek = stateList.get(k);
if ((statei & statek) > 0 || (statej & statek) > 0) {
continue;
}
return true;
}
}
}
return false;
}
public void dfs(int depth, int sum, int state) {
if (sum == edge) {
stateList.add(state);
return;
}
if (sum > edge) {
return;
}
if (depth == matchsticks.length) {
return;
}
dfs(depth + 1, sum, state);
dfs(depth + 1, sum + this.matchsticks[depth], state | (1 << depth));
}
}