LeetCode Weekly Contest 13-Matchsticks to Square【中】
Matchsticks to Square
Rememberthe story of Little Match Girl? By now, you know exactly what matchsticks thelittle match girl has, please find out a way you can make one square by usingup all those matchsticks. You should not break any stick, but you can link themup, and each matchstick must be used exactly one time.
Yourinput will be several matchsticks the girl has, represented with their sticklength. Your output will either be true or false, to represent whether you cansave this little girl or not.
Example1:
Input:[1,1,2,2,2]
Output:true
Explanation:You can form a square with length 2, one side of the square came two stickswith length 1.
Example2:
Input:[3,3,3,3,4]
Output:false
Explanation:You cannot find a way to form a square with all the matchsticks.
Note:
Thelength sum of the given matchsticks is in the range of 0 to 10^9.
Thelength of the given matchstick array will not exceed 15.
Rememberthe story of Little Match Girl? By now, you know exactly what matchsticks thelittle match girl has, please find out a way you can make one square by usingup all those matchsticks. You should not break any stick, but you can link themup, and each matchstick must be used exactly one time.
Yourinput will be several matchsticks the girl has, represented with their sticklength. Your output will either be true or false, to represent whether you cansave this little girl or not.
Example1:
Input:[1,1,2,2,2]
Output:true
Explanation:You can form a square with length 2, one side of the square came two stickswith length 1.
Example2:
Input:[3,3,3,3,4]
Output:false
Explanation:You cannot find a way to form a square with all the matchsticks.
Note:
Thelength sum of the given matchsticks is in the range of 0 to 10^9.
Thelength of the given matchstick array will not exceed 15.
class Solution {
public:
bool solve(int s1, int s2, int s3, int s4, int pos)
{
if(pos == size_ && s1 == s2 && s2 == s3 && s3 == s4)//
{
return true;
}
else if(pos == size_) return false;
if( (s1 != sum_ / 4 && s1 > sum_ / 4 - nums_[pos]) || (s2 != sum_ / 4 && s2 > sum_ / 4 - nums_[pos]) ||
(s3 != sum_ / 4 && s3 > sum_ / 4 - nums_[pos]) || (s4 != sum_ / 4 && s4 > sum_ / 4 - nums_[pos]) )
return false;
if( (s1 != sum_ / 4 && 2147483647 - s1 < nums_[pos]) || (s2 != sum_ / 4 && 2147483647 - s2 < nums_[pos]) ||
(s3 != sum_ / 4 && 2147483647 - s3 < nums_[pos]) || (s4 != sum_ / 4 && 2147483647 - s4 < nums_[pos]) )
return false;
if(solve(s1 + nums_[pos], s2, s3, s4, pos + 1) || solve(s1, s2 + nums_[pos], s3, s4, pos + 1) ||
solve(s1, s2, s3 + nums_[pos], s4, pos + 1) || solve(s1, s2, s3, s4 + nums_[pos], pos + 1))
return true;
return false;
}
bool makesquare(vector& nums) {
size_ = nums.size();
nums_ = std::move(nums);
if(size_ < 4) return false;
sort(nums_.begin(), nums_.end());
sum_ = 0;
for(int i = 0; i < size_; i ++)
sum_ += nums_[i];
//std::cout< nums_;
long long sum_;
};