Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
Your input will be several matchsticks the girl has, represented with their stick length. Your output will either be true or false, to represent whether you can save this little girl or not.
Note:
The length sum of the given matchsticks is in the range of 0 to 10^9.
The length of the given matchstick array will not exceed 15.
Solution:
some condition needs to be true if the final result is true:
1: the total number of the elements in the array needs to be at least 4;
2: the average needs to be divided by 4 exactly;
3: the largest elements in the array cannot be larger than the average;
4: the most difficult part: those elements has to be packaged exactly and fully into 4 containers with the same size of the average, and each elements can only be used once;
Code:
class Solution { public: bool makesquare(vector<int>& nums) { if(nums.size()<4) return false; int ave = 0, left = 0, len = 0; for(int i=0; i<nums.size(); ++i){ ave +=nums[i]/4; left +=nums[i]%4; } if(left%4) return false; else len = ave + left/4; for(auto i:nums){ if(i>len) return false; } vector<int> side(4, 0); return fitDSF(nums, 0, len, side); } private: bool fitDSF(vector<int> &n, int ind, int l, vector<int> &s){ if(ind == n.size()) return true; for(int i=0; i<4; ++i){ if(i>0&&s[i] == s[i-1]) continue;//if not included, will cause TLE... if(s[i] + n[ind] <= l){ s[i] += n[ind]; if(fitDSF(n, ind+1, l, s)) return true; s[i] -= n[ind]; } } return false; } };
No comments :
Post a Comment