题目描述:
还记得童话《卖火柴的小女孩》吗?现在,你知道小女孩有多少根火柴,请找出一种能使用所有火柴拼成一个正方形的方法。不能折断火柴,可以把火柴连接起来,并且每根火柴都要用到。
输入为小女孩拥有火柴的数目,每根火柴用其长度表示。输出即为是否能用所有的火柴拼成正方形。
示例 1:
输入: [1,1,2,2,2] 输出: true 解释: 能拼成一个边长为2的正方形,每边两根火柴。示例 2:
输入: [3,3,3,3,4] 输出: false 解释: 不能用所有火柴拼成一个正方形。注意:
- 给定的火柴长度和在
0
到10^9
之间。- 火柴数组的长度不超过15。
算法:
回溯法,剪枝,深度优先搜索
class Solution {
public:
bool makesquare(vector<int>& nums) {
int sum = 0;
for(auto& num:nums)
sum += num;
if(nums.size() < 4 || sum % 4 !=0)
return false;
vector<int>target(4, sum/4);
sort(nums.rbegin(), nums.rend());
return dfs(nums, 0, target);
}
bool dfs(vector<int>& nums, int index, vector<int>& target)
{
int len = nums.size();
if(index == len)
return true;
for(int i=0; i<4; i++)
{
if(target[i] >= nums[index])
{
target[i] -= nums[index];
if(dfs(nums, index+1, target))
return true;
target[i] += nums[index];
}
}
return false;
}
};
参考: