nikunjsoni

473

Jun 15th, 2021
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     bool makesquare(vector<int>& sticks) {
  4.         int sum = 0;
  5.         for(auto num: sticks)
  6.             sum += num;
  7.         if(sum%4) return false;
  8.         sort(sticks.rbegin(), sticks.rend());
  9.         vector<int> sums(4, 0);
  10.         return dfs(sum/4, sums, 0, sticks);
  11.     }
  12.    
  13.     bool dfs(int target, vector<int> &sums, int idx, vector<int> &sticks){
  14.         if(idx == sticks.size()){
  15.             if(sums[0] == target && sums[1] == target && sums[2] == target)
  16.                 return true;
  17.             else
  18.                 return false;
  19.         }
  20.         for(int i=0; i<4; i++){
  21.             if(sticks[idx]+sums[i] > target) continue;
  22.             sums[i] += sticks[idx];
  23.             if(dfs(target, sums, idx+1, sticks)) return true;
  24.             sums[i] -= sticks[idx];
  25.         }
  26.         return false;
  27.     }
  28.    
  29. };
Advertisement
Add Comment
Please, Sign In to add comment