You are given an integer array matchsticks
where matchsticks[i]
is the length of the ith
matchstick. You want to use all the matchsticks to make one 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.
Example 1:
Input: matchsticks = [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: matchsticks = [3,3,3,3,4] Output: false Explanation: You cannot find a way to form a square with all the matchsticks.
Constraints:
1 <= matchsticks.length <= 15
1 <= matchsticks[i] <= 108
Related Topics:
Array, Dynamic Programming, Backtracking, Bit Manipulation, Bitmask
// OJ: https://leetcode.com/problems/matchsticks-to-square/
// Author: github.com/lzl124631x
// Time: O(N * 2^N)
// Space: O(2^N)
class Solution {
public:
bool makesquare(vector<int>& A) {
int sum = accumulate(begin(A), end(A), 0), N = A.size();
if (sum % 4 || *max_element(begin(A), end(A)) > sum / 4) return false;
sum /= 4;
sort(begin(A), end(A), greater<>()); // Try rocks before sands
vector<int> dp(1 << N, -1); // -1 unvisited, 0 invalid, 1 valid
dp[(1 << N) - 1] = 1;
function<bool(int, int)> dfs = [&](int mask, int target) {
if (dp[mask] != -1) return dp[mask];
dp[mask] = 0;
if (target == 0) target = sum;
for (int i = 0; i < N && !dp[mask]; ++i) {
if ((mask >> i & 1) || A[i] > target) continue;
dp[mask] = dfs(mask | (1 << i), target - A[i]);
}
return dp[mask];
};
return dfs(0, sum);
}
};
Let target = sum(A) / 4
, which is the target length of each edge.
We use DFS to try to fill each A[i]
into different edges.
Two optimizations here:
- The
unordered_set<int> seen
is used to prevent handling the same edge value again. For example, assumeedge = [1, 1, 1, 1]
, and now we are trying to add a stick of length2
to it. Adding2
to either1
will yield the same result. So we just need to add to a edge with length1
once. - Sorting the sticks in descending order will make it converge faster because it's easy to fill in sands but hard to fill in peddles; filling peddles first will fail faster.
// OJ: https://leetcode.com/problems/matchsticks-to-square/
// Author: github.com/lzl124631x
// Time: O(4^N)
// Space: O(N * SUM(A))
class Solution {
public:
bool makesquare(vector<int>& A) {
long v[4] = {}, sum = accumulate(begin(A), end(A), 0L);
if (sum % 4 || *max_element(begin(A), end(A)) > sum / 4) return false;
sum /= 4;
sort(begin(A), end(A), greater<>()); // Try rocks before sands
function<bool(int)> dfs = [&](int i) {
if (i == A.size()) return true;
unordered_set<long> seen;
for (int j = 0; j < 4; ++j) {
if (A[i] + v[j] > sum || seen.count(v[j])) continue;
seen.insert(v[j]);
v[j] += A[i];
if (dfs(i + 1)) return true;
v[j] -= A[i];
}
return false;
};
return dfs(0);
}
};
Or
// OJ: https://leetcode.com/problems/matchsticks-to-square/
// Author: github.com/lzl124631x
// Time: O(4^N)
// Space: O(N * SUM(A))
class Solution {
public:
bool makesquare(vector<int>& A) {
long v[4] = {}, sum = accumulate(begin(A), end(A), 0L), N = A.size();
if (sum % 4) return false;
sum /= 4;
sort(begin(A), end(A), greater<>()); // Try rocks before sands
function<bool(int)> dfs = [&](int i) {
if (i == N) return true;
for (int j = 0; j < 4; ++j) {
if (A[i] + v[j] > sum) continue;
v[j] += A[i];
if (dfs(i + 1)) return true;
v[j] -= A[i];
if (v[j] == 0) break; // Simply don't visit empty bucket again. This takes less space but longer time.
}
return false;
};
return dfs(0);
}
};