Leetcode 473. Matchsticks to Square
You are given an integer array matchsticks
where matchsticks[i]
is the length of the i-th
matchstick. You want to use all the matchsticks to form a square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
Return true
if you can make this square and false
otherwise.
matchsticks = [1,1,2,2,2]
true
matchsticks = [3,3,3,3,4]
false
1 <= matchsticks.length <= 15
1 <= matchsticks[i] <= 10^8
1 <= matchsticks[i]
).false
.false
, since a square requires 4 sides.false
.sum / 4
.sum / 4
.#include <vector>
#include <algorithm>
class Solution {
public:
bool makesquare(std::vector<int>& matchsticks) {
int sum = 0;
for (int stick : matchsticks) {
sum += stick;
}
if (sum % 4 != 0) {
return false;
}
int sideLength = sum / 4;
std::sort(matchsticks.begin(), matchsticks.end(), std::greater<int>());
std::vector<int> sides(4, 0); // Initialize 4 sides
return dfs(matchsticks, sides, sideLength, 0);
}
private:
bool dfs(std::vector<int>& matchsticks, std::vector<int>& sides, int sideLength, int index) {
if (index == matchsticks.size()) {
return sides[0] == sideLength && sides[1] == sideLength
&& sides[2] == sideLength && sides[3] == sideLength;
}
for (int i = 0; i < 4; ++i) {
if (sides[i] + matchsticks[index] <= sideLength) {
sides[i] += matchsticks[index];
if (dfs(matchsticks, sides, sideLength, index + 1)) {
return true;
}
sides[i] -= matchsticks[index];
}
// If this side already has no matchsticks, break to avoid redundancy
if (sides[i] == 0) break;
}
return false;
}
};
O(n log n)
where n
is the number of matchsticks.O(4^n)
, where n
is the number of matchsticks. But the actual performance can be significantly better with pruning.This solution combines initial checks with efficient backtracking to determine if the matchsticks can form a square.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?