1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public: bool dfs(int index, vector<int> &matchsticks, vector<int> &edges, int len) { if (index == matchsticks.size()) { return true; } for (int i = 0; i < edges.size(); i++) { edges[i] += matchsticks[index]; if (edges[i] <= len && dfs(index + 1, matchsticks, edges, len)) { return true; } edges[i] -= matchsticks[index]; } return false; }
bool makesquare(vector<int> &matchsticks) { int totalLen = accumulate(matchsticks.begin(), matchsticks.end(), 0); if (totalLen % 4 != 0) { return false; } sort(matchsticks.begin(), matchsticks.end(), greater<int>());
vector<int> edges(4); return dfs(0, matchsticks, edges, totalLen / 4); } };
|