Approach
Depth-first search
For Matchsticks to Square, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 32 lines of C++ from the credited upstream file 473.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 bool makesquare(vector<int>& matchsticks) {4 if (matchsticks.size() < 4)5 return false;6 7 const int perimeter = accumulate(matchsticks.begin(), matchsticks.end(), 0);8 if (perimeter % 4 != 0)9 return false;10 11 ranges::sort(matchsticks, greater<>());12 return dfs(matchsticks, 0, vector<int>(4, perimeter / 4));13 }14 15 private:16 bool dfs(const vector<int>& matchsticks, int selected, vector<int>&& edges) {17 if (selected == matchsticks.size())18 return ranges::all_of(edges, [](int edge) { return edge == 0; });19 20 for (int i = 0; i < 4; ++i) {21 if (matchsticks[selected] > edges[i])22 continue;23 edges[i] -= matchsticks[selected];24 if (dfs(matchsticks, selected + 1, std::move(edges)))25 return true;26 edges[i] += matchsticks[selected];27 }28 29 return false;30 }31};32