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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| class Solution { public: const static int maxn = 1e5 + 10; const static int maxm = 1e5 + 10; const static int INF = 0x3f3f3f3f; bool dfs(int step, int cur, int& len, vector<int> &nums, int mask, int cnt) { if (cnt == 3) return true; if (cur == len) return dfs(0, 0, len, nums, mask, cnt + 1); for (int i = step; i < nums.size(); ++i) { if (mask & (1 << i)) continue; if (cur + nums[i] <= len) { if (dfs(i + 1, cur + nums[i], len, nums, mask | (1 << i), cnt)) { return true; } if (cur == 0 || cur + nums[i] == len) return false; } while (i + 1 < nums.size() && nums[i + 1] == nums[i]) i++; } return false; } bool makesquare(vector<int> &matchsticks) { int sum = 0; for (int i = 0; i < matchsticks.size(); ++i) { sum += matchsticks[i]; } if (sum % 4) return false; int len = sum / 4; sort(matchsticks.begin(), matchsticks.end(), greater<int>()); return dfs(0, 0, len, matchsticks, 0, 0); } };
|