A trickier DFS, with a little bit complex recursion param tweak, and what's more important is pruning strategies.. or your code will TLE.
class Solution { bool go(vector<bool> &m, int edge, int eleft, int etgt, vector<int> &in, int taken) { if(edge > 4) return false; if(edge == 4 && eleft == etgt && in.size() == taken) { return true; } int last = -1; for(int i = in.size()-1; i >=0; i --) { if(m[i]) continue; if(in[i] > eleft) continue; // because it is sorted if(in[i] == last) continue; // important: critical pruning. if(in[i] <= eleft) { m[i] = true; bool fit = in[i] == eleft; if(go(m, edge + (fit?1:0), fit?etgt:(eleft-in[i]), etgt, in, taken + 1)) { return true; } m[i] = false; last = in[i]; } } return false; } public: bool makesquare(vector<int>& nums) { if(nums.size() < 4) return false; int sum = accumulate(nums.begin(), nums.end(), 0); if(!sum || (sum % 4)) return false; sort(nums.begin(), nums.end()); if (nums.back() > (sum/4)) return false; vector<bool> m(nums.size(), false); int tgt = sum / 4; return go(m, 0, tgt, tgt, nums, 0); } };