473. Matchsticks to Square
Medium
28136FavoriteShare
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 exactlyone 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 could make one square using all the matchsticks the little match girl has.
Example 1:
Input: [1,1,2,2,2] Output: true Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.
Example 2:
Input: [3,3,3,3,4] Output: false Explanation: You cannot find a way to form a square with all the matchsticks.
Note:
- The length sum of the given matchsticks is in the range of
0to10^9. - The length of the given matchstick array will not exceed
15.
题意:给你一堆长短不一的小木棒,问你这些小木棒能否摆成一个正方形。
题解:两种方法:1.dfs + 减枝; 2.位运算
先说位运算:

结果如下:

class Solution {
public:
bool makesquare(vector<int>& nums) {
if (nums.size() < 4) return false;
int target = 0;
for (int i = 0; i < nums.size(); i++){
target += nums[i];
}
if(target % 4) return false;
else target /= 4;
vector <int> ok_subset;
vector <int> ok_half;
int all = 1 << nums.size();//枚举所有子集
for (int i = 1; i <= all; i++){
int sum = 0;
for (int j = 0; j < nums.size(); j++){
if((i & (1 << j))){
sum += nums[j];
}
}
if(sum == target){
ok_subset.push_back(i);
}
}
for (int i = 0; i < ok_subset.size(); i++){
for (int j = i + 1; j < ok_subset.size(); j++){
if((ok_subset[i] & ok_subset[j]) == 0){
ok_half.push_back(ok_subset[i] | ok_subset[j]);
}
}
}
for (int i = 0; i < ok_half.size(); i++){
for (int j = i+1; j < ok_half.size(); j++){
if((ok_half[i] & ok_half[j]) == 0){
return true;
}
}
}
return false;
}
};
方法二:dfs + 减枝
class Solution {
public:
bool cmp(int a, int b){
return a > b;
}
bool makesquare(vector<int>& nums) {
int sum = 0;
for (int i = 0; i < nums.size(); i++){
sum += nums[i];
}
if(sum % 4 || sum == 0) return false;
sort(nums.rbegin(), nums.rend());
return dfs(0, 0, 0, 0, 0, sum / 4, nums);
}
bool dfs(int index, int s1, int s2, int s3, int s4, int s, vector<int>& nums){
if(index == nums.size()){
if(s1 == s2 && s2 == s3 && s3 == s4){
return true;
} else {
return false;
}
}
if(s1 > s || s2 > s || s3 > s || s4 >s){//减枝
return false;
}
for (int i = index; i < nums.size(); i++){
if(dfs(i+1, s1+nums[i], s2, s3, s4, s, nums)){
return true;
} else if(dfs(i+1, s1, s2+nums[i], s3, s4, s, nums)){
return true;
} else if(dfs(i+1, s1, s2, s3+nums[i], s4, s, nums)){
return true;
} else if(dfs(i+1, s1, s2, s3, s4+nums[i], s, nums)){
return true;
} else {
return false;
}
}
return false;
}
};
本文探讨如何利用给定长度的火柴棍拼成一个正方形的问题,提供两种解决方案:位运算和深度优先搜索加剪枝。文章详细介绍了算法的实现过程,包括判断输入是否可行、使用位运算寻找可能的子集组合以及通过深度优先搜索进行递归尝试。
1808

被折叠的 条评论
为什么被折叠?



