473 Matchsticks to Square 火柴拼正方形

时间:2023-03-09 06:53:01
473 Matchsticks to Square 火柴拼正方形

还记得童话《卖火柴的小女孩》吗?现在,你知道小女孩有多少根火柴,请找出一种能使用所有火柴拼成一个正方形的方法。不能折断火柴,可以把火柴连接起来,并且每根火柴都要用到。
输入为小女孩拥有火柴的数目,每根火柴用其长度表示。输出即为是否能用所有的火柴拼成正方形。
示例 1:
输入: [1,1,2,2,2]
输出: true
解释: 能拼成一个边长为2的正方形,每边两根火柴。

示例 2:
输入: [3,3,3,3,4]
输出: false
解释: 不能用所有火柴拼成一个正方形。
注意:
    给定的火柴长度和在 0 到 10^9之间。
    火柴数组的长度不超过15。
详见:https://leetcode.com/problems/matchsticks-to-square/description/

C++:

class Solution {
public:
bool makesquare(vector<int>& nums)
{
if (nums.empty() || nums.size() < 4)
{
return false;
}
int sum = accumulate(nums.begin(), nums.end(), 0);
if (sum % 4 != 0)
{
return false;
}
vector<int> sums(4, 0);
sort(nums.rbegin(), nums.rend());
return helper(nums, sums, 0, sum / 4);
}
bool helper(vector<int>& nums, vector<int>& sums, int pos, int target) {
if (pos >= nums.size())
{
return sums[0] == target && sums[1] == target && sums[2] == target;
}
for (int i = 0; i < 4; ++i) {
if (sums[i] + nums[pos] > target)
{
continue;
}
sums[i] += nums[pos];
if (helper(nums, sums, pos + 1, target))
{
return true;
}
sums[i] -= nums[pos];
}
return false;
}
};

参考:https://www.cnblogs.com/grandyang/p/6238425.html